tags:

views:

183

answers:

9

Hello,

I have a string "10/15/2010"

I want to split this string into 10, 15, 2010 using c#, in VS 2010. i am not sure how to do this. If someone can tell me what function to use, it would be awesome.

Thank you so much!!

+4  A: 
string str = "10/15/2010";
string[] parts = str.split('/');

You now have string array parts that holds parts of that initial string.

Cipi
+3  A: 

Take a look at String.Split().

string date = "10/15/2010";
string[] dateParts = date.Split('/');
Joshua Rodgers
+10  A: 

You probably want to call

DateTime date = DateTime.Parse("10/15/2010", CultureInfo.InvariantCulture);
SLaks
Good call SLaks, While everyone is suggesting on [whether to use a shoe or a bottle](http://weblogs.asp.net/alex_papadimoulis/archive/2005/05/25/408925.aspx) you suggest a hammer.
Scott Chamberlain
This is definitely a much better choice for converting date strings into actual dates.
Joshua Rodgers
The question was not how to parse a string to a date, it was how to split a string that happens to look like a date string into its components. Is there any evidence in the question that he wants a date? What if he wants to use the results as-is, not as dates?
Cyberherbalist
@Cyberherbalist: That's why I said _probably_. There are enough other answers that I didn't see the point in giving a `Split` call.
SLaks
Fair enough....
Cyberherbalist
A: 

"10/15/2010".Split('/')

sirmak
A: 

Assuming you wanted the "split" elements to be strings as well:

string date = "10/15/2010";

string[] split = date.Split('/');
mmsmatt
A: 

var date = "10/15/2010";

var split = date.Split('/')

Noel Abrahams
A: 

Simple:

string[] pieces = "10/15/2010".Split ('/');

Using String.Split.

Pete
+1  A: 

Depending on how you plan to consume the information, you can choose strings, like has already been suggested, or parse it into a date then pull out the pieces.

DateTime date = DateTime.Parse("10/15/2010");
int y = date.year;
int m = date.Month;
int d = date.Day;
Brad
Won't work when the current culture uses DMY or YMD order...
Christian Hayter
+2  A: 

Or do like a saw in a recent program (in Fortran which I am translating to C# below) ..

string[] parts = "10/15/2010".Split('/');
if( parts[0] == "01" ) month = 1;
if( parts[0] == "02" ) month = 2;
if( parts[0] == "03" ) month = 3;
if( parts[0] == "04" ) month = 4;
...

you get the idea. It kills me when people code it something crazy instead of calling a built in function to do the same thing.

( please don't flag me down, this is just a joke, not a real answer to the question )

jalexiou
just make sure that [the two digit representation of December isn't '12', but 'December'](http://thedailywtf.com/Articles/Cold-Date-Conversion.aspx) :)
jb