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

后端 未结 4 1049
醉话见心
醉话见心 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 02:09

    You can use the DateTimeFormatInfo.CurrentInfo ShortDatePattern and ShortTimePattern to do the translation:

    // Change the culture to something different
    Thread.CurrentThread.CurrentCulture = new CultureInfo("de-AT");
    DateTime test_datetime = new DateTime(2008, 10, 2, 3, 22, 12);
    string s_date = test_datetime.ToString(DateTimeFormatInfo.CurrentInfo);
    
    // For specifically the short date and time
    string s_date1 = 
       test_datetime.ToString(DateTimeFormatInfo.CurrentInfo.ShortDatePattern);
    string s_time1 = 
       test_datetime.ToString(DateTimeFormatInfo.CurrentInfo.ShortTimePattern);
    
    // Results
    // s_date1 == 02.10.2008
    // s_time1 == 03:22
    

提交回复
热议问题