Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Parse DD/MM/YYYY 24 Hour Clock

Tags:

.net

datetime

DateTime.Parse fails on

 15/08/2000 16:58

Any thoughts?

I need to parse dates and get some international.

DD/MM/YYYY will not flop to 24 hour clock

MM/DD/YYYY will accept 24 hour clock

15/08/2000 4:58 PM will parse

From the Kibbee answer I looked at using other cultures. I use Regex to determine if it is dd/MM and if so use culture fr-FR.

like image 944
paparazzo Avatar asked Apr 26 '12 00:04

paparazzo


2 Answers

Try DateTime.ParseExact():

var result = DateTime.ParseExact(dateString,
                                 "dd/MM/yyyy HH:mm",
                                 new CultureInfo("en-US"));
like image 137
Justin Niessner Avatar answered Oct 24 '22 23:10

Justin Niessner


You should probably be using DateTime.ParseExact to parse the date if you know the exact format that you expect the date to be in. For your purposes, the following will probably work.

string dateString, format;  
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;

dateString = "15/08/2000 16:58"
format = "dd/MM/yyyy HH:mm"
result = DateTime.ParseExact(dateString, format, provider);

Change to above. Changed hh to HH because HH signifies 24 hour time. If you don't use a leading zero, then simply use H. For more information on creating format strings see this article.

Also from the linked MSDN article, it appears as though the format "g" should work.

dateString = "15/06/2008 08:30";
format = "g";
CultureInfo provider = new CultureInfo("fr-FR");
DateTime result = DateTime.ParseExact(dateString, format, provider);
like image 29
Kibbee Avatar answered Oct 25 '22 00:10

Kibbee