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
Using
hhvshwill do a leading 0. Same withmmfor minutes. If you want seconds, you can usess.There are many more. You should check the MSDN documentation for the full reference:
https://msdn.microsoft.com/library/zdtaw1bw.aspx