Search code examples
c#datetimemilliseconds

Why is my DateTime.Now.Millisecond value always "000"?


I want my millisecond value to always be three characters long, so I'm padding it, where necessary, with "0"s:

private String getPlatypusFileName(String billNum)
{
    const string basePortion = "Platypus_";
    String PlatypusFileName;
    DateTime dt = DateTime.Now;
    int Year = dt.Year;
    int Month = dt.Month;
    int Day = dt.Day;
    int Hour = dt.Hour;
    int Minute = dt.Minute;
    int Second = dt.Second;
    int Millisecond = dt.Millisecond;
    String paddedBillNum = Prepad(6, billNum);
    String mon = Prepad(2, Month.ToString());
    String day = Prepad(2, Day.ToString());
    String hour = Prepad(2, Hour.ToString());
    String min = Prepad(2, Minute.ToString());
    String sec = Prepad(2, Second.ToString());
    String milli = Prepad(3, Millisecond.ToString());
    PlatypusFileName = String.Format("{0}{1}_{2}{3}{4}{5}{6}{7}_{8}.xml", 
        basePortion, paddedBillNum, Year, mon, day, hour, min, sec, milli);
    return PlatypusFileName;
}

private String Prepad(int finalSize, String originalVal)
{
    String paddedVal = originalVal;
    while (paddedVal.Length < finalSize)
    {
        paddedVal = "0" + paddedVal;
    }
    return paddedVal;
}

...but I'm always getting vals with three "0"s for the millisecond portion; the returned values are like so:

Platypus_000003_20141008145606_000.xml

Why would that be?


Solution

  • Why don't you use standard datetime.toString("special_format_string"). Learn methods of the string class, also learn about formats. You don't need even Prepad method.

    All you need is one simple method:

        private String getPlatypusFileName(String billNum)
        {
            const string basePortion = "Platypus_";
            String PlatypusFileName;
            DateTime dt = DateTime.Now;
            PlatypusFileName = String.Format("{0}{1}_{2}.xml",
                basePortion, billNum.PadLeft(6,'0'), dt.ToString("yyyyMMddHHmmss_fff"));
            return PlatypusFileName;
        }
    

    More over, don't use const if you don't know what it for. Also I'm sure that the base type of billNum source also is int, so you do not need any special method, you already have method string.Format(), just use it wisely. All your code can be replaced with one statement:

    int billNum = 23;
    string PlatypusFileName = string.Format("Platypus_{0:D6}_{1:yyyyMMddHHmmss_fff}.xml", billNum, DateTime.Now);