Magic strings for converting DateTime to string Using C#

前端 未结 4 1058

I was greeted with a nasty bug today. The task is pretty trivial, all I needed to do is to convert the DateTime object to string in \"yyyymmdd\" format

相关标签:
4条回答
  • 2021-01-27 15:09
    String.Format("{0:0000}{1:00}{2:00}", dateTime.Year, dateTime.Month, dateTime.Day);
    

    You could use this instead, I prefer the terse format though. Instead of 00 you can also use MM for specific month formatting (like in DateTime.ToString()).

    0 讨论(0)
  • 2021-01-27 15:15
    return dateTime.Year.ToString() + dateTime.Month + dateTime.Day;
    

    You don't need to keep adding empty strings, string+number returns string already and addition is interpreted from left to right.

    Do note that that line doesn't return what you think it does, what you really want is:

    return dateTime.Year.ToString("0000") + dateTime.Month.ToString("00") 
        + dateTime.Day.ToString("00");
    
    0 讨论(0)
  • 2021-01-27 15:25

    If that format string bugs you that much, at least make sure it is in one place. Encapsulate it e.g. in an extension method:

    public string ToMyAppsPrefferedFormat(this DateTime date) {
      return date.ToString("ddMMyyyy");
    }
    

    Then you can say date.ToMyAppsPrefferedFormat()

    0 讨论(0)
  • 2021-01-27 15:30

    See here: .NET Custom Date and Time Format Strings

    0 讨论(0)
提交回复
热议问题