How to get Hours and Minutes as two digits with leading zero from DateTime object?

beginer
beginer
236 Points
68 Posts

How to get Hours and Minutes as two digits with leading zero from DateTime object?

I'm trying following code formulate the file path:

var filePath = $"{DateTime.UtcNow.Year}/{DateTime.UtcNow.Month}/{DateTime.UtcNow.Day}/{DateTime.UtcNow.Hour}/{DateTime.UtcNow.Minute}/{Guid.NewGuid()}";

But it's not returning always two digits from hours, minutes, etc. I want path like "2021/04/07/02/04"

 

Views: 146
Total Answered: 1
Total Marked As Answer: 1
Posted On: 07-Apr-2021 06:00

Share:   fb twitter linkedin
Use .ToString() i.e. for hour use DateTime.UtcNow.ToString("HH");
 - Rahul Maurya  09-Apr-2021 01:57
Answers
Rashmi
Rashmi
Member
166 Points
33 Posts
         
DateTime.UtcNow.ToString("hh:mm") // for non military time
DateTime.UtcNow.ToString("HH:mm") // for military time (24 hour clock)

Using hh will do a leading 0. Same with mm for minutes will do a leading zero. 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

You can refer to DateTime.ToString()

Posted On: 10-Apr-2021 08:38
Thanks
 - beginer  17-Apr-2021 01:21
 Log In to Chat