I'm using CultureInfo()
to get format of DateTime
CultureInfo culture = new CultureInfo(CultureInfo.CurrentCulture.Name);
someDateTime.ToString("d", culture));
How to get custom formats and not to lose separator which comes with CultureInfo()
?
CodePudding user response:
According to the documentation for DateTimeFormatInfo.DateSeparator
:
If a custom format string includes the "/" format specifier, the DateTime.ToString method displays the value of DateSeparator in place of the "/" in the result string.
So just use a custom date/time format string with slashes, and they will be replaced automatically.
Example:
var someDateTime = new DateTime(1900, 12, 21);
Console.WriteLine(someDateTime.ToString("d/M", new CultureInfo("en-US")));
Console.WriteLine(someDateTime.ToString("d/M", new CultureInfo("nl")));
Console.WriteLine(someDateTime.ToString("yyy/M", new CultureInfo("en-US")));
Console.WriteLine(someDateTime.ToString("yyy/M", new CultureInfo("nl")));
Output:
21/12
21-12
1900/12
1900-12
Just be aware that this probably isn't a great idea. The separator is not the only meaningful difference between cultures' date representations. 5/6
means May 6 to Americans, but it means June 5 to most Europeans (even those which use the same date separator).
CodePudding user response:
You can provide a format when you call ToString
on DateTime
objects.
e.g.:
someDateTime.ToString("MM-yyyy"); // produces a formatted date like 12-1900
Formatting Info: https://www.c-sharpcorner.com/blogs/date-and-time-format-in-c-sharp-programming1
CodePudding user response:
You can also specify the separator property of the DateTimeFormatInfo object, like so:
DateTime someDateTime = DateTime.Now;
CultureInfo culture = new CultureInfo("en-US");
DateTimeFormatInfo dtfi = culture.DateTimeFormat;
dtfi.DateSeparator = "-";
someDateTime.ToString("d", culture);