Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse C# string to DateTime

I have a string like this: 250920111414

I want to create a DateTime object from that string. As of now, I use substring and do it like this:

string date = 250920111414;

int year = Convert.ToInt32(date.Substring(4, 4));
int month = Convert.ToInt32(date.Substring(2, 2));
...
DateTime dt = new DateTime(year, month, day ...);

Is it possible to use string format, to do the same, without substring?

like image 768
hogni89 Avatar asked Sep 28 '11 09:09

hogni89


2 Answers

Absolutely. Guessing the format from your string, you can use ParseExact

string format = "ddMMyyyyHHmm";

DateTime dt = DateTime.ParseExact(value, format, CultureInfo.InvariantCulture);

or TryParseExact:

DateTime dt;
bool success = DateTime.TryParseExact(value, format, 
                     CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

The latter call will simply return false on parse failure, instead of throwing an exception - if you may have bad data which shouldn't cause the overall task to fail (e.g. it's user input, and you just want to prompt them) then this is a better call to use.

EDIT: For more details about the format string details, see "Custom Date and Time Format Strings" in MSDN.

like image 194
Jon Skeet Avatar answered Oct 05 '22 03:10

Jon Skeet


You could use:

DateTime dt = DateTime.ParseExact(
                  date, 
                  "ddMMyyyyHHmm",
                  CultureInfo.InvariantCulture);
like image 24
Marco Avatar answered Oct 05 '22 02:10

Marco