36

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 etc

Alex R.
  • 4,564
  • 4
  • 29
  • 40
BreakHead
  • 10,062
  • 34
  • 108
  • 163

4 Answers4

59

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.

Community
  • 1
  • 1
Oded
  • 477,625
  • 97
  • 867
  • 998
  • 3
    The call `CultureInfo.CurrentCulture.DateTimeFormat;` does not return a string value. The final call should be `string sysDateFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;` in case you are looking for the System short date format. – Joe Almore Jan 15 '14 at 19:45
  • @JoeAlmore - thanks for the comment. Answer updated. – Oded Jan 15 '14 at 19:50
19

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;
patridge
  • 25,996
  • 17
  • 90
  • 131
RcMan
  • 854
  • 7
  • 15
4

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.

phoog
  • 40,767
  • 6
  • 75
  • 112
0

Use below:

System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern

Rajesh Kumar
  • 61
  • 1
  • 8