简体   繁体   中英

DateTime.Now Date Format and Windows Settings

I have a console application written in C# that makes use of DateTime.Now. With the Windows Region set to "English (United States)", the short date output is M/d/yyyy. I have an instance of my application running on a machine with the culture format set to "English (Canada)" and the short date format set to dd/MM/yyyy. Since I want consistency within my application across different servers, I changed the short date format in Windows' Region settings to M/d/yyyy. However, my application is still outputting DateTime.Now as dd/MM/yyyy. Is there something else that needs to be changed for my application to output in the format I specified?

I do this in various places but here is an example:

TimeZoneInfo customTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime thisTime = TimeZoneInfo.ConvertTime(DateTime.Now, customTimeZone);
//The below output is not formatted how the Windows Region short date is specified.
Console.Writeline(thisTime);

In this case, my DateTime is not formatted how its specified in the Windows Region settings.

If you can handle the date being as a string, I don't recommand you use the settings to get past this problem. You should use something like this :

DateTime.Now.ToString("MM\/dd\/yyyy")

This way you have full control over the output independently of region settings.

You can change the culture of the current thread as follows on application start. This affects the date format, currency format, etc.

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

See MSDN: Globalization for more information (see section on Dates and Times).

First, a little correction to the answer by @phadaphunk: the line

DateTime.Now.ToString("MM\/dd\/yyyy");

will cause an error: 'unrecognized escape sequence'. So, it can be corrected as

DateTime.Now.ToString(@"MM\/dd\/yyyy");

The more general way to specify the DateTime format as detailed in MSDN article http://msdn.microsoft.com/en-us/library/8kb3ddd4%28v=vs.110%29.aspx would be the following:

String.Format("{0:MM/dd/yyyy}",DateTime.Now);

with CultureInfo.InvariantCulture explicitly specified as suggested by @Joe, or thread-specific CurrentCulture set to CultureInfo("en-US") as suggested by @async.

Hope this will help. Best regards,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM