I have a variable date in C# that I create using
var date = new DateTime(2000, 01, 01)
The result of the date is 01/01/2000 -> this is the month/date/year
I want the result is in format date/month/year
I know I can format this one.. But is there another way around that date will automatically in format date/month/year without manually format the date?
If you look in the source code for the .NET framework for the DateTime
type you'll find this line:
private ulong dateData;
That's how the DateTime
is stored. There is no format.
From your code, new DateTime(2000, 01, 01)
, the underlying value for that DateTime
is 630822816000000000
.
But, when you go to display a date it would be exceedingly unhelpful if .ToString()
produced 630822816000000000
instead of something like 01/01/2000
.
So, still in the source, you'll find this override:
public override string ToString()
{
return DateTimeFormat.Format(this, (string) null, DateTimeFormatInfo.CurrentInfo);
}
Effectively, the .ToString()
method uses the current culture's info for formatting dates.
You can always do this to ensure you get consistent results:
var date = new DateTime(2000, 4, 16);
var us = date.ToString(CultureInfo.GetCultureInfo("en-us"));
var au = date.ToString(CultureInfo.GetCultureInfo("en-au"));
This results in the following formats respectively:
4/16/2000 12:00:00 AM 16/04/2000 12:00:00 AM
In .net Date formats are based on your machine localization. So you have two options.
1) change your machine language and culture settings.
2) change threads CultureInfo to render date in correct formate.
For more information see https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(v=vs.110).aspx
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.