04 February, 2008

Convert a datetime string into DateTime object

The problem: you have a string presenting a datetime value and you want convert it into DateTime object.

An answer: of course, the simplest way is you can parse that string into your fields and contruct new DateTime object then. But if the string is something like "12/8/2008 23:17", so how can you parse this string into month,day,year,hour and minute.

But .Net Framework already support you for such task. You can use DateTime.ParseExact() for this purpose. Here is sample code

1 DateTime convertedDateTime = DateTime.ParseExact(

2 "20/08/2008 13:10",

3 "MM/dd/yyyy HH:mm",

4 System.Globalization.CultureInfo.CurrentCulture);

5 Console.WriteLine(string.Format("Day: {0}", convertedDateTime.Day));

6 Console.WriteLine(string.Format("Month: {0}", convertedDateTime.Month));

7 Console.WriteLine(string.Format("Hour: {0}", convertedDateTime.Hour));


Pay a little attention in line 3 & 4, you must provide exactly format of your date time string. Acctually, I don't know why we need an IFormatProvider in here :-) (so I use default one as you can see)

Hope this tip will help you


Powered by ScribeFire.

2 comments:

Chubby said...

This is my problem, especially, when I set a field in database is DateTime type. hmm, it always display naughty type as: 12:00:00 00:00.... now I can convert it as I want kaka ^^. Thank Xi Trummmm.

Duy Lam said...

you're welcome. i like your avatar, it's cute