0

I am trying to get a time variable that always uses 4 digits to represent the time as per below.

I have tried the following

 string slotStartTimeInMilitaryFormat = $"{timeSlotsStartTime.Hour}{timeSlotsStartTime.Minute}";

Problem is that I need 1AM to be 0100 and 9PM to be 2100 in other words always a 4 digit representation of the time

but my code makes it 100 instead of 0100 etc.

How can I ensure I always get the 4 digit representation

0000 0030 0100

1300 1330 1400

Matt Douhan
  • 2,053
  • 1
  • 21
  • 40

2 Answers2

2

Try...

string slotStartTimeInMilitaryFormat = timeSlotsStartTime.ToString("HHmm");
JohnG
  • 9,259
  • 2
  • 20
  • 29
-1

Refer to the answers at How can I format a number into a string with leading zeros?

Use String Interpolation:

$"{15:00000}"; // "00015"

Thieu
  • 44
  • 3