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
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
If you only want the hours and minutes as separated values you can use
DateTime.Now.Hour.ToString("00.##") + ":" + DateTime.Now.Minute.ToString("00.##");
You should check out MSDN's Standard Date And Time Format Strings
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