2

How to convert a string such as "10/19/2017 12:00:00 AM" into a DateTime? I used Convert.ToDateTime() but It gives an error as;

String was not recognized as a valid DateTime.

How to fix?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
NHK
  • 107
  • 2
  • 11

3 Answers3

3

You should use ParseExact

var result = DateTime.ParseExact("10/19/2017 12:00:00 PM", "MM/dd/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • Since `AM` and `PM` designators are used for [12-hour clock](https://en.wikipedia.org/wiki/12-hour_clock), I think it would be better to use `hh` instead of `HH` specifiers. – Soner Gönül Oct 19 '17 at 06:21
2

Convert.ToDateTime doesn't have specified formatting to parse, you need to use DateTime.ParseExact or DateTime.TryParseExact:

// DateTime.ParseExact
DateTime date = DateTime.ParseExact("10/19/2017 12:00:00 PM", "MM/dd/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);

// DateTime.TryParseExact
DateTime.TryParseExact("10/19/2017 12:00:00 PM", "MM/dd/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
  • Since `AM` and `PM` designators are used for [12-hour clock](https://en.wikipedia.org/wiki/12-hour_clock), I think it would be better to use `hh` instead of `HH` specifiers. – Soner Gönül Oct 19 '17 at 06:21
2
 String MyString= "10/19/2017 12:00:00 AM";
        DateTime MyDateTime = new DateTime();
        MyDateTime = DateTime.ParseExact(MyString, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

Format goes as below

d - Numeric day of the month without a leading zero.

dd - Numeric day of the month with a leading zero.

ddd - Abbreviated name of the day of the week.

dddd - Full name of the day of the week.

f,ff,fff,ffff,fffff,ffffff,fffffff - Fraction of a second. The more Fs the higher the precision.

h - 12 Hour clock, no leading zero.

hh - 12 Hour clock with leading zero.

H - 24 Hour clock, no leading zero.

HH - 24 Hour clock with leading zero.

m - Minutes with no leading zero. mm - Minutes with leading zero.

M - Numeric month with no leading zero.

MM - Numeric month with a leading zero.

MMM - Abbreviated name of month.

MMMM - Full month name.

s - Seconds with no leading zero. ss - Seconds with leading zero.

t - AM/PM but only the first letter. tt - AM/PM ( a.m. / p.m.)

y - Year with out century and leading zero.

yy - Year with out century, with leading zero.

yyyy - Year with century.

zz - Time zone off set with +/-.

Ansil F
  • 284
  • 1
  • 8
  • You don't need `DateTime MyDateTime = new DateTime();` because you will create new date anyway `DateTime MyDateTime = DateTime.ParseExact(...` will be enough. – Fabio Oct 19 '17 at 04:35