Converting a timestamp string to a DateTime object in C #

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

+5
source share
5 answers

The input line looks like in a format en-usthat M/d/yyyy h/mm/ss tt. You must use the correct CultureInfoinstance when 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");
+6
source
var date = DateTime.ParseExact("5/1/2012 3:38:27 PM", 
    "M/d/yyyy h:mm:ss tt",
    CultureInfo.InvariantCulture);
+7
source

DateTime.ParseExact:

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);

DateTime . .

:

01.05.2012 15:38:27

Be aware that this result may vary depending on the culture you use. Since mine Culture tr-TR, the date operator is .our culture.

Here DEMO.

+4
source

http://www.codeproject.com/Articles/14743/Easy-String-to-DateTime-DateTime-to-String-and-For
this may help you. There you can find a detailed explanation of the parameters of ParseExact.

0
source

All Articles