How to get System DateTime format?

后端 未结 3 1914
梦谈多话
梦谈多话 2020-12-13 13:55

I am looking for a solution to get system date time format.

For example: if I get DateTime.Now? Which Date Time Format is this using? DD/MM/YYYY

相关标签:
3条回答
  • 2020-12-13 14:36

    The System.DateTime.Now property returns a System.DateTime. This is stored in memory in a binary format that most programmers in most circumstances have no need to think about. When you display a DateTime value, or convert it to a string for any other reason, it is converted according to a format string, which can specify any format you like.

    In this last sense, the answer to your question "if I get DateTime.Now, which Date Time Format is this using?" is "it is not using any DateTime format at all, because you haven't formatted it yet".

    You specify the format by calling an overload of ToString, or (optionally) if you use System.String.Format. There is a default format, as well, so you don't always have to specify the format. If you're asking about how to determine the default format, then you should look at Oded's answer.

    0 讨论(0)
  • 2020-12-13 14:38

    If it has not been changed elsewhere, this will get it:

    string sysFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
    

    If using a WinForms app, you may also look at the UICulture:

    string sysUIFormat = CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern;
    

    Note that DateTimeFormat is a read-write property, so it can be changed.

    0 讨论(0)
  • 2020-12-13 14:42

    The answers above are not fully correct.

    I had a situation that my Main thread and my UI thread were forced to be in "en-US" culture (by design). My Windows DateTime format was "dd/MM/yyyy"

    string sysFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
    string sysUIFormat = CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern;
    

    returned "MM/dd/yyyy", but I wanted to get my real Windows format. The only way I was able to do so is by creating a dummy thread.

    System.Threading.Thread threadForCulture = new System.Threading.Thread(delegate(){} );
    string format = threadForCulture.CurrentCulture.DateTimeFormat.ShortDatePattern;
    
    0 讨论(0)
提交回复
热议问题