I need to convert 12 hours format time (am/pm) to 24 hours format time, e.g. 01:00 PM to 13:00 using C#. How can I convert it?
From 0:00 (midnight) to 0:59, add 12 hours and use am. From 1:00 to 11:59, just add am after the time. From 12:00 to 12:59, just add pm after the time. From 13:00 to 0:00, subtract 12 hours and use pm.
Add 12 to the first hour of the day and include "AM." In 24-hour time, midnight is signified as 00:00. So, for midnight hour, add 12 and the signifier "AM" to convert to 12-hour time. This means that, for example, 00:13 in 24-hour time would be 12:13 AM in 12-hour time.
If you need to convert a string to a DateTime you could try
DateTime dt = DateTime.Parse("01:00 PM"); // No error checking
or (with error checking)
DateTime dt; bool res = DateTime.TryParse("01:00 PM", out dt);
Variable dt
contains your datetime, so you can write it
dt.ToString("HH:mm");
Last one works for every DateTime var you have, so if you still have a DateTime, you can write it out in this way.
You'll want to become familiar with Custom Date and Time Format Strings.
DateTime localTime = DateTime.Now; // 24 hour format -- use 'H' or 'HH' string timeString24Hour = localTime.ToString("HH:mm", CultureInfo.CurrentCulture);
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