Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.ParseExact - UK date and time

Tags:

c#

datetime

I'm trying to parse the following UK format DateTime string: 24/01/2013 22:00

However, I keep getting this error:

String was not recognized as a valid DateTime.

CultureInfo.CurrentCulture returns "en-GB" which is correct

Here is my code

    [TestMethod]
    public void TestDateTimeParse()
    {
        DateTime tester = DateTime.ParseExact("24/01/2013 22:00", "d/M/yyyy hh:mm", CultureInfo.CurrentCulture);

        int hours = tester.Hour;
        int minutes = tester.Minute;

        Assert.IsTrue(true);
    }
like image 880
JGilmartin Avatar asked Jan 22 '13 12:01

JGilmartin


2 Answers

hh is for 12 hour clocks. You should be using HH instead.

DateTime.ParseExact("24/01/2013 22:00", 
                    "d/M/yyyy HH:mm", // <-- here
                    CultureInfo.CurrentCulture)
like image 120
Oded Avatar answered Oct 14 '22 01:10

Oded


"hh" is for The hour, using a 12-hour clock from 01 to 12

"HH" is for The hour, using a 24-hour clock from 00 to 23

Try with like this;

public static void Main(string[] args)
{
    DateTime tester = DateTime.ParseExact("24/01/2013 22:00", "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);
}

Here is a DEMO.

Also you can check out Custom Date and Time Format Strings from MSDN.

like image 40
Soner Gönül Avatar answered Oct 14 '22 01:10

Soner Gönül