Format .NET DateTime “Day” with no leading zero

后端 未结 2 1887
陌清茗
陌清茗 2020-12-01 23:44

For the following code, I would expect result to equal 2, because the MSDN states that \'d\' \"Represents the day of the month as a number from 1 through 31. A sing

相关标签:
2条回答
  • 2020-12-01 23:56

    Rather than using string formatting strings, how about using the Day property

    DateTime myDate = new DateTime(2009,6,4)
    int result = myDate.Day;
    

    Or if you really needed the result in string format

    string result = myDate.Day.ToString();
    

    If you are looking to get a specific date part out of a date object rather than a formatted representation of the date, I prefer to use the properties (Day, Month, Year, DayOfWeek, etc.) It makes reading the code a bit easier (particularly if someone else is reading/maintaining it that doesn't have the various formatting codes memorized)

    0 讨论(0)
  • 2020-12-02 00:12

    To indicate that this is a custom format specifier (in contrast to a standard format specifier), it must be two characters long. This can be accomplished by adding a space (which will show up in the output), or by including a percent sign before the single letter, like this:

    string result = myDate.ToString("%d");
    

    See documentation

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