weixin_39788572
weixin_39788572
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

diff
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

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

该提问来源于开源项目:dotnet/runtime

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

5条回答

  • 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:
    csharp
    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:

    csharp
    DateTime.Today.ToString(someDateTimeFormatInfo.ShortDatePattern);
    
    点赞 评论 复制链接分享

相关推荐