I have timestamp strings in the following format 5/1/2012 3:38:27 PM
. How do I convert it to a DateTime object in c#

- 2,226
- 3
- 31
- 60
-
It would be helpful if you posted what you have tried. – Security Hound Apr 19 '13 at 12:23
5 Answers
var date = DateTime.ParseExact("5/1/2012 3:38:27 PM",
"M/d/yyyy h:mm:ss tt",
CultureInfo.InvariantCulture);

- 38,383
- 7
- 71
- 92
You input string looks like in en-us
format, which is M/d/yyyy h/mm/ss tt
. You have to use proper CultureInfo
instance while parsing:
var ci = System.Globalization.CultureInfo.GetCultureInfo("en-us");
var value = DateTime.Parse("5/1/2012 3:38:27 PM", ci);
or
var ci = new System.Globalization.CultureInfo("en-us");

- 124,003
- 15
- 196
- 263
-
Thanks, this should work but I am developing on Windows Phone. GetCultureInfo does not contain in `System.Globalization.CultureInfo`? – PutraKg Apr 19 '13 at 11:14
-
`DateTime.Parse` seems to expect a `System.IFormatProvider` so `ci` is marked as invalid argument – PutraKg Apr 19 '13 at 11:25
-
Ah sorry my mistake, you are correct. I was using a date variable which wasn't a string object. – PutraKg Apr 19 '13 at 11:35
-
Try to use DateTime.ParseExact
method like;
string s = "5/1/2012 3:38:27 PM";
DateTime date = DateTime.ParseExact(s, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
Console.WriteLine(date);
Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
Output will be;
01.05.2012 15:38:27
Be aware, this output can change based which Culture you used. Since my Culture
is tr-TR
, the date operator is .
our culture.
Here is a DEMO
.

- 97,193
- 102
- 206
- 364
http://www.codeproject.com/Articles/14743/Easy-String-to-DateTime-DateTime-to-String-and-For
this maybe helps you. There you can find a detailled explanation of the ParseExact parameters.

- 385
- 2
- 8