Rajeev Kumar
Rajeev Kumar

Reputation: 4963

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 ?

Upvotes: 2

Views: 16082

Answers (5)

Rohidas Kadam
Rohidas Kadam

Reputation: 446

Try this:

DateTime dateTime = DateTime.Now;

string strMinFormat = dateTime.ToString("hh:mm:ss tt"); // 12 hours format
string strMaxFormat = dateTime.ToString("HH:mm:ss tt"); // 24 hours format

Upvotes: 2

Adel Mourad
Adel Mourad

Reputation: 1545

using System.Globalization;

//Your datetime variable value for example or you can get it from the database
//2019-05-31 03:00:00 PM
DateTime datetime = DateTime.ParseExact("2019-05-31 03:00:00 PM", "yyyy-MM-dd hh:mm:ss tt", CultureInfo.InvariantCulture); 

//2019-05-31 15:00:00
string _24HoursFormat = datetime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

//15:00:00
string _24HoursFormatTimeOnly = datetime.ToString("HH:mm:ss", CultureInfo.InvariantCulture);

Upvotes: 0

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'

Upvotes: 3

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391724

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

Upvotes: 6

Nuffin
Nuffin

Reputation: 3972

The problem you're having is that H looks for the hour in 24-hour-format and ignores the daypart specifier entirely. Use the 12-hour-format specifier h instead.

Upvotes: 1

Related Questions