Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get 24 Hour time format in datetime variable

I am using DateTime.TryParseExact function to get the datetime value in variable using following code

 DateTime dt;
 CultureInfo provider = CultureInfo.InvariantCulture;
 System.Globalization.DateTimeStyles style = DateTimeStyles.None;
 string[] format = new string[] { "d/MMM/yy H:m:s tt","d-MMM-yy H:m:s tt" }; 
 string strDate = "24-May-13 12:03:03 AM";
 DateTime.TryParseExact(strDate, format, provider, style, out dt);

Now what it does it parse the datetime correctly and give me result 24-May-2013 12:03:03 But i want it should return me like this 24-May-2013 00:03:033

How can i do this ?

like image 550
Rajeev Kumar Avatar asked Sep 11 '26 07:09

Rajeev Kumar


2 Answers

Use the lower-case h for your formats, test the following in LINQPad:

void Main()
{
    CultureInfo provider = CultureInfo.InvariantCulture;
    System.Globalization.DateTimeStyles style = DateTimeStyles.None;
    string[] format = new string[] { "d/MMM/yy h:m:s tt","d-MMM-yy h:m:s tt" }; 
    //                                         ^                   ^
    //                                         +------ here -------+
    string strDate = "24-May-13 12:03:03 AM";

    DateTime dt;
    if (DateTime.TryParseExact(strDate, format, provider, style, out dt))
    {
        dt.Dump();
        dt.Hour.Dump();
    }
}

Outputs:

24.05.2013 00:03:03
0
like image 55
Lasse V. Karlsen Avatar answered Sep 12 '26 20:09

Lasse V. Karlsen


You should use

HH:mm:ss

for displaying time (along with the date) in 24 hour format.

Warning:

As the accepted answer pointed out, this works fine if you are trying to parse a date that is already in an 24 hour format. Otherwise, you use lowercase 'h'

like image 42
now he who must not be named. Avatar answered Sep 12 '26 20:09

now he who must not be named.



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!