How do I get today's date in C# in mm/dd/yyyy format?

后端 未结 8 1956
长情又很酷
长情又很酷 2020-12-29 01:00

How do I get today\'s date in C# in mm/dd/yyyy format?

I need to set a string variable to today\'s date (preferably without the year), but there\'s got to be a bette

相关标签:
8条回答
  • 2020-12-29 01:06
    DateTime.Now.ToString("M/d/yyyy");
    

    http://msdn.microsoft.com/en-us/library/8kb3ffffd4.aspx

    0 讨论(0)
  • 2020-12-29 01:11

    If you want it without the year:

    DateTime.Now.ToString("MM/DD");
    

    DateTime.ToString() has a lot of cool format strings:

    http://msdn.microsoft.com/en-us/library/aa326721.aspx

    0 讨论(0)
  • 2020-12-29 01:13

    Or without the year:

    DateTime.Now.ToString("M/dd")
    
    0 讨论(0)
  • 2020-12-29 01:15
    DateTime.Now.Date.ToShortDateString()
    

    I think this is what you are looking for

    0 讨论(0)
  • 2020-12-29 01:16

    Not to be horribly pedantic, but if you are internationalising the code it might be more useful to have the facility to get the short date for a given culture, e.g.:-

    using System.Globalization;
    using System.Threading;
    
    ...
    
    var currentCulture = Thread.CurrentThread.CurrentCulture;
    try {
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-us");
      string shortDateString = DateTime.Now.ToShortDateString();
      // Do something with shortDateString...
    } finally {
      Thread.CurrentThread.CurrentCulture = currentCulture;
    }
    

    Though clearly the "m/dd/yyyy" approach is considerably neater!!

    0 讨论(0)
  • 2020-12-29 01:16
    DateTime.Now.Date.ToShortDateString()
    

    is culture specific.

    It is best to stick with:

    DateTime.Now.ToString("d/MM/yyyy");
    
    0 讨论(0)
提交回复
热议问题