Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Date Time Hours and Minutes with leading Zero

Tags:

c#

I'm trying to figure out the simplest code to add leading zeros on to the hours and minutes from the DateTime.Now function. I need to combine only the hours and minutes, and I don't need the rest of the date.

Whats the best way to do this?

My code looks like this:

DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString();

However I get data such as 16:4 for 4:04PM and I need it to look like 16:04. I'm familiar with the msdn articles on datetime formatting but I didn't see anything that addresses this specifically.

Is it possible combining `DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString();

If not how would I pull only the HH:MM out of DateTime.Now easily?

Looking for least lines of code possible because this is something that I will be utilizing often. Thanks

like image 829
Encryption Avatar asked Apr 26 '12 21:04

Encryption


3 Answers

DateTime.Now.ToString("hh:mm") // for non military time
DateTime.Now.ToString("HH:mm") // for military time (24 hour clock)

Using hh vs h will do a leading 0. Same with mm for minutes. If you want seconds, you can use ss.

MM - Month with leading 0
M - Month without leading 0
dd - Day with leading 0
d - Day without leading 0
yyyy - 4 Digit year
yy - 2 Digit year
HH - Military Hour with leading 0
H - Military Hour without leading 0
hh - Hour with leading 0
h - Hour without leading 0
mm - Minute with leading 0
m - Minute without leading 0
ss - Second with leading 0
s - Second without leading 0
tt - AM / PM 

There are many more. You should check the MSDN documentation for the full reference: https://msdn.microsoft.com/library/zdtaw1bw.aspx

like image 94
Dismissile Avatar answered Nov 16 '22 13:11

Dismissile


If you only want the hours and minutes as separated values you can use

DateTime.Now.Hour.ToString("00.##") + ":" + DateTime.Now.Minute.ToString("00.##");
like image 7
Farouk ElKhabbaz Avatar answered Nov 16 '22 14:11

Farouk ElKhabbaz


You should check out MSDN's Standard Date And Time Format Strings

like image 3
fguchelaar Avatar answered Nov 16 '22 12:11

fguchelaar