Is there a culture-safe way to get ToShortDateString() and ToShortTimeString() with leading zeros?

后端 未结 4 1054
醉话见心
醉话见心 2020-12-31 01:20

I know that I could use a format string, but I don\'t want to lose the culture specific representation of the date/time format. E.g.

5/4/2011 | 2:06 PM | ...

4条回答
  •  心在旅途
    2020-12-31 01:58

    You could also override the CurrentThread.CurrentCulture class. At the beginning of your program you call this method:

        private void FixCurrentDateFormat()
        {
            var cc = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
            var df = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat;
            df.FullDateTimePattern = PatchPattern(df.FullDateTimePattern);
            df.LongDatePattern = PatchPattern(df.LongDatePattern);
            df.ShortDatePattern = PatchPattern(df.ShortDatePattern);
            //change any other patterns that you could use
    
            //replace the current culture with the patched culture
            System.Threading.Thread.CurrentThread.CurrentCulture = cc;
        }
    
        private string PatchPattern(string pattern)
        {
            //modify the pattern to your liking here
            //in this example, I'm replacing "d" with "dd" and "M" with "MM"
            var newPattern = Regex.Replace(pattern, @"\bd\b", "dd");
            newPattern = Regex.Replace(newPattern, @"\bM\b", "MM");
            return newPattern;
        }
    

    With this, anywhere you display a date as a string in your program it will have the new format.

提交回复
热议问题