开发者

How to get System DateTime format?

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 e开发者_Python百科tc


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.


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;


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.


If you want both date and time in the formatted string, you can simply use DateTime.ToString() or DateTimeOffset.ToString(). This will format the DateTime as per the CurrentCulture. It basically combines ShortDate and LongTime from the CurrentCulture's DateTimeFormat.

Have a look at the documentation.

Example:

If your system uses dd-MM-yyyy format for ShortDate and HH:mm:ss format for LongTime, following code will print 24-02-2023 18:15:22

var dateTimeObject = DateTime.UtcNow;
var formattedString = dateTimeObject.ToString();
Console.WriteLine("Date and Time: " + formattedString);

Note: In case you are using DateTimeOffset, it will also add the offset to the formatted string. Ex: 24-02-2023 18:23:22 +05:30


Use below:

System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜