2021-01-11 09:15

DateTime overloads for specifying the culture for formatting

Background and Motivation

I would like to get the "short date string" using a specific culture. It returns the string in the format "mm/dd/YYYY" but I want "yyyy-MM-dd" but there is no method overload, so I have to resort to workarounds such as DateTime.Today.ToString("yyyy-MM-dd").

Proposed API

public struct DateTime : ...
     public string ToLongDateString();
+    public string ToLongDateString(IFormatProvider provider);
     public string ToLongTimeString();
+    public string ToLongTimeString(IFormatProvider provider);
     public string ToShortDateString();
+    public string ToShortDateString(IFormatProvider provider);

Usage Examples

var culture = CultureInfo.GetCultureInfo("sv-SE");
var shortDate = DateTime.Today.ToShortDateString(culture);


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • weixin_39620118 weixin_39620118 4月前

    same; my eyes were scanning for Now or UtcNow in the example. :)

    点赞 评论 复制链接分享
  • weixin_39553156 weixin_39553156 4月前
    • I'm going to assume the definition is:
    public DateTime Today => Now.Date;

    ... the point was how to not use a raw string, more than anything else.

    点赞 评论 复制链接分享
  • weixin_39620118 weixin_39620118 4月前

    -Muse, I meant DateTime.Now.ToShortDateString instead of DateTime.ToShortDateString to access the non-static method.

    点赞 评论 复制链接分享
  • weixin_39737233 weixin_39737233 4月前

    I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.

    点赞 评论 复制链接分享
  • weixin_39553156 weixin_39553156 4月前

    A better example of current code would probably be:

    点赞 评论 复制链接分享