I' like to return this short date in the US format, the current culture of my application is en-GB
, but I'd like it in en-US
.
Here's the code I have so far:
DateTime.Now.AddYears(-2).ToShortDateString();
I' like to return this short date in the US format, the current culture of my application is en-GB
, but I'd like it in en-US
.
Here's the code I have so far:
DateTime.Now.AddYears(-2).ToShortDateString();
You need to ensure that you are using the right culture format string for this to happen.
One way to get this format directly from the culture is:
CultureInfo.GetCultureInfo("en-US").DateTimeFormat.ShortDatePattern
For me this returns M/d/yyyy
.
var usShortDatePattern =
CultureInfo.GetCultureInfo("en-US").DateTimeFormat.ShortDatePattern;
DateTime.Now.AddYears(-2).ToString(usShortDatePattern);
The benefit of doing this is that if a user has overridden the Short Date Pattern for en-US
in their control panel (Region and Language), they will get the formatting they want.
Taken from the documentation:
DateTime.Now.AddYears(-2).ToString("d", new CultureInfo("en-US"));
Use .ToString()
extension method and enter the format:
DateTime.Now.AddYears(-2).ToString("M/d/yyyy");
Custom date format options are documented here:
var culture = new CultureInfo("en-us");
string formatedDate = DateTime
.Now
.AddYears(-2)
.ToString(culture.DateTimeFormat.ShortDatePattern, culture);
"I want to apply the en-US short-date-pattern":
DateTime.Now.AddYears(-2).ToString("d", CultureInfo.GetCultureInfo("en-US"));
"I want to apply the pattern M/d/yyyy regardless of whether .NET thinks that's the short-pattern for en-US or not:
DateTime.Now.AddYears(-2).ToString(@"M\/d\/yyyy", CultureInfo.InvariantCulture)
(Same result as above, but if what you are thinking of as "the US format" was actually MM/dd/yyyy, which is also used in the US, then that's the approach you want, but with @"MM\/dd\/yyyy"
instead of @"M\/d\/yyyy"
.
Finally, "I want to find out the en-US short-date-pattern for use with another call:
CultureInfo.GetCultureInfo("en-US").DateTimeFormat.ShortDatePattern