Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime parse with custom format

Tags:

c#

I am trying to parse a datetime value using this:

DateTime insertedDateTime = DateTime.ParseExact(tokens[0] + " " + tokens[1], "yyyy-MM-dd mm:hh:ss", CultureInfo.InvariantCulture);

//tokens[0] = 2013-09-05 
//tokens[1] = 07:23:32

I am getting this error:

String was not recognized as a valid DateTime.

Any help would be appreciated.

like image 837
Akshay J Avatar asked Feb 13 '26 11:02

Akshay J


1 Answers

you should write:

DateTime insertedDateTime = DateTime.ParseExact(tokens[0] + " " + tokens[1], "yyyy-MM-dd mm:HH:ss", CultureInfo.InvariantCulture);

because hh means 12h time and HH means 24h time and putting 23 as hour in 12h time is invalid :)

Of course if you are sure that hours are second in your time and you don't want to write HH:mm:ss or hh:mm:ss (for 12h format)

DEMO here

like image 52
Kamil Budziewski Avatar answered Feb 15 '26 02:02

Kamil Budziewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!