What is a less Kludgy way to Conditionally Prepend a "0" to dateTime Elements?

I want my string YearMonthDayHourMinuteSecondMillisecond to be of this format ("0" prepended where necessary):

20140227142807

...but this:

string YearMonthDayHourMinuteSecond = string.Format("{0}{1}{2}_{3}{4}{5}", dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);

...gives me "2" (instead of "02") for February, etc. such as:

2014227142807

I can solve it this way:

string YearMonthDayHourMinuteSecondMillisecond = string.Format("{0}{1}{2}_{3}{4}{5}{6}", dt.Year, ConditionalZeroForepad(dt.Month), ConditionalZeroForepad(dt.Day), ConditionalZeroForepad(dt.Hour), ConditionalZeroForepad(dt.Minute), ConditionalZeroForepad(dt.Second);

private string ConditionalZeroForepad(string s)
{
   if (s.Length < 2)
   {
       return string.Format("0{1}", s);   
   }
}

...but that's 9X Uglier than a Bag of Butts.

What is a more genteel way to accomplish this?

Jon Skeet
people
quotationmark

Don't use string.Format at all - use DateTime.ToString():

string text = dt.ToString("yyyyMMddHHmmssfff", CultureInfo.InvariantCulture);

Or to just go down to seconds:

string text = dt.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture);

(Your variable name suggests you want milliseconds, but your sample suggests you don't.)

Note the use of CultureInfo.InvariantCulture to ensure you always use the Gregorian calendar, even if the current culture of the thread is one which has a different default calendar. (Obviously if you want a different calendar, that's a different matter.)

See custom date and time format strings for more information.

people

See more on this question at Stackoverflow