1

i have string format of date looks like "04/16/2014 19:10", i want to convert it to DateTime.

i tried, below codes, but it didn't work. i got error like "String was not recognized as a valid DateTime."

How to convert to datetime

DateTime dt1 = DateTime.Parse(DateTimeString);

DateTime dt = System.Convert.ToDateTime(DateTimeString);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Naruto
  • 9,476
  • 37
  • 118
  • 201

2 Answers2

4

The problem is Parse, as you are using it, will take into account the current culture of the machine which means (depending on where you are) that date could be interpreted differently.

Whenever you are parsing specific dates you should use ParseExact or TryParseExact, that way you leave no room for ambiguity on how the date should be interpreted (regardless of culture)

DateTime dt;
if (DateTime.TryParseExact("04/16/2014 19:10", "MM/dd/yyyy hh:mm", 
    CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
    // date was parsed correctly, use `dt`
}
James
  • 80,725
  • 18
  • 167
  • 237
1

You may want to use ParseExact and specify the format yourself:

DateTime d = DateTime.ParseExact("04/16/2014 19:10", "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139