Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string time like (0740) into 12 hours (AM,PM) time format like (07:40 AM)

Tags:

c#

asp.net

How can i convert string time into 12 hours (AM,PM) time format? Like if input string will like "2320" than i want answer like "11:20 PM".

like image 426
Ashish Avatar asked Jan 01 '10 20:01

Ashish


People also ask

How to convert a string to a DateTime?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

What is FFF in date format?

The "fff" custom format specifier represents the three most significant digits of the seconds fraction; that is, it represents the milliseconds in a date and time value.

How do you convert to military time?

To convert standard 12 hour format to military time For instance, 2:15 am becomes 02:15 hours. If the 12 hour time is in the pm, we will add 12 hours and remove the “pm”. For example - 2:30 pm, here we add 12 hours to the hours section(2 + 12 = 14) and we get the military time of 14:30 hours.


2 Answers

string s = DateTime.ParseExact("2320","HHmm",CultureInfo.CurrentCulture)
       .ToString("hh:mm tt");
like image 104
Marc Gravell Avatar answered Sep 30 '22 09:09

Marc Gravell


I'm sure its been mentioned many times, but here is the reference for the to string parameters for Datetime here.

In Marc's answer, there is a leading zero in the hours if it is a single digit hour.

string s = DateTime.ParseExact("2320", "HHmm").ToString("h:mm tt");

The above would provide the format we're used to seeing from most digital clocks these days.

like image 31
Todd Richardson Avatar answered Sep 30 '22 11:09

Todd Richardson