Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert AM/PM time to 24 hours format?

Tags:

c#

datetime

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?

like image 348
nmathur Avatar asked Dec 01 '11 07:12

nmathur


People also ask

How do you convert am pm to hours?

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.

What is 12.30 am in 24 hour format?

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.


2 Answers

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.

like image 119
Marco Avatar answered Oct 05 '22 15:10

Marco


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); 
like image 29
bobbymcr Avatar answered Oct 05 '22 14:10

bobbymcr