Magic strings for converting DateTime to string Using C#

前端 未结 4 1067

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: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");
    

提交回复
热议问题