Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert timestamp string to DateTime object in c#

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#

like image 230
PutraKg Avatar asked Apr 19 '13 11:04

PutraKg


3 Answers

var date = DateTime.ParseExact("5/1/2012 3:38:27 PM", 
    "M/d/yyyy h:mm:ss tt",
    CultureInfo.InvariantCulture);
like image 89
Eren Ersönmez Avatar answered Sep 25 '22 13:09

Eren Ersönmez


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");
like image 38
MarcinJuraszek Avatar answered Sep 26 '22 13:09

MarcinJuraszek


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.

like image 40
Soner Gönül Avatar answered Sep 24 '22 13:09

Soner Gönül