Home > Net >  0 Character Problem in the beggining DateTime
0 Character Problem in the beggining DateTime

Time:02-03

I got every part of date in the code that you can see below. But the problem is if we consider today's date I need day and month as 02 not as 2. I need that 0 char in the beggining. How can I manage it?

DateTime dategift = DateTime.Now;
                var year = dategift.Year.ToString();
                var month = dategift.Month.ToString();
                var day = dategift.Day.ToString();
                var hour = dategift.Hour.ToString();
                var min = dategift.Minute.ToString();
                var sec = dategift.Second.ToString();

CodePudding user response:

use the Zero placeholder

string day = dategift.Day.ToString("00");

or the "dd" custom format specifier

string day = dategift.ToString("dd");

CodePudding user response:

If you're wanting to format the date, you can do so without pulling out all the various values as strings.

Something like:

DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
  • Related