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".
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.
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.
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.
string s = DateTime.ParseExact("2320","HHmm",CultureInfo.CurrentCulture)
.ToString("hh:mm tt");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With