How to use custom DateTime string format for time without the date portion?

The below code works for all of the custom date format strings except for the ones relating to time. The ToString returns zeroes for any custom format except the ones containing dates. Is it possible to use the custom formats for time in the way that I’m attempting or do I need to do manual manipulation of the string?

protected string PopulateDateInFilename(string filename) {
        // The filename can have a date format template, replace template with data here
        Dictionary<string, string> dateDictionary = new Dictionary<string, string>() {
            {"[yyyymmdd]",  "yyyyMMdd"},
            {"[yyyy-mm-dd]",  "yyyy-MM-dd"},
            {"[yyyy.mm.dd]",  "yyyy.MM.dd"},
            {"[mmddyyyy]",  "MMddyyyy"},
            {"[mm-dd-yyyy]",  "MM-dd-yyyy"},
            {"[mm.dd.yyyy]",  "MM.dd.yyyy"},
            {"[hhmmss]",  "HHmmss"},
            {"[hh-mm-ss]",  "HH-mm-ss"},
            {"[hh.mm.ss]",  "HH.mm.ss"},
            {"[hhmm]",  "HHmm"},
            {"[hh-mm]",  "HH-mm"},
            {"[hh.mm]",  "HH.mm"},
            {"[mmyyyy]",  "MMyyyy"},
            {"[mm-yyyy]",  "MM-yyyy"},
            {"[mm.yyyy]",  "MM.yyyy"},
            {"[yyyymm]",  "yyyyMM"},
            {"[yyyy-mm]",  "yyyy-MM"},
            {"[yyyy.mm]",  "yyyy.MM"},
            {"[ddmm]",  "ddMM"},
            {"[dd-mm]",  "dd-MM"},
            {"[dd.mm]",  "dd.MM"},
            {"[mmdd]",  "MMdd"},
            {"[mm-dd]",  "MM-dd"},
            {"[mm.dd]",  "MM.dd"}
        };

        foreach (KeyValuePair<string, string> entry in dateDictionary) {
            if (filename.IndexOf(entry.Key, 0, StringComparison.OrdinalIgnoreCase) != -1) {
                string formattedDate = (DateTime.Today).ToString(entry.Value);
                // case insensitive replace
                string result = Regex.Replace(
                    filename,
                    Regex.Escape(entry.Key),
                    formattedDate.Replace("$", "$$"),
                    RegexOptions.IgnoreCase
                );
                filename = result;
                break;
            }
        };

        return filename;
    }

>Solution :

DateTime.Today returns

An object that is set to today’s date, with the time component set to 00:00:00.

You want DateTime.Now, I guess.

Leave a Reply