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

后端 未结 4 1044
醉话见心
醉话见心 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:48

    I wrote a method to do that kind of transformations :

    /// 
    /// Transform DateTime into short specified format
    /// 
    /// string : input DateTime
    /// 
    /// string - optional : ouput format - default "d"
    /// 
    public static string ConvertDateTimeToShortDate(string strDateTime, CultureInfo cultureInfo, string strFormat="d")
    {
      var dateTime = DateTime.MinValue;
      return DateTime.TryParse(strDateTime, out dateTime) ? dateTime.ToString(strFormat, cultureInfo) : strDateTime;
    }
    

    To call it, for time format :

    DateTimeTools.ConvertDateTimeToShortDate(DateTime.Today.ToString(),
                CultureInfo.InvariantCulture,"t");
    

    Hope it can help u

提交回复
热议问题