How about this solution:
// Get a default DateTimeFormat
var dateTimeFormat = CultureInfo.GetCultureInfo("en-US").DateTimeFormat;
// Clone it to make it writeable
dateTimeFormat = (DateTimeFormatInfo)dateTimeFormat.Clone();
// Change the DateSeparator
dateTimeFormat.DateSeparator = "-";
// Output it as normal
var output = DateTime.Now.ToString("g", dateTimeFormat);
I think what the most people don't know you can get a writeable version of a culture by creating a new object by calling the Clone()
method.
Update
As Tim said, you can also call it this way:
// Get a default DateTimeFormat
var dateTimeFormat = new CultureInfo("en-US").DateTimeFormat;
// Change the DateSeparator
dateTimeFormat.DateSeparator = "-";
// Output it as normal
var output = DateTime.Now.ToString("g", dateTimeFormat);
This works, cause we created a new CultureInfo
derived from a given culture. The reason why the first one is read-only, comes from the fact, that in the first case we'll get a reference to some statically created instance somewhere deep down in the framework and with the Clone()
call we create a fresh class with the same settings. In the second approach we create directly the fresh class, but say we'd like to get all the settings out of a specific culture.
So at the end of the day, both versions are doing the same thing just described in other words. If there is a performance difference between both versions i can't tell, but i think this can be neglected.
Update 2
After reading Toms last comment he tries something like this:
// Get a default DateTimeFormat
var dateTimeFormat = new CultureInfo("en-US").DateTimeFormat;
// Change the DateSeparator
dateTimeFormat.DateSeparator = "-";
// Output it as normal
var output = DateTime.Now.ToString(dateTimeFormat.ShortDatePattern);
Which leads to a wrong output. This comes, because within dateTimeFormat.ShortDatePattern
is just a normal string containing M/d/yyyy
. So it is the same as calling DateTime.Now.ToString("M/d/yyyy")
.
Due to the fact, that the /
will be replaced by the DateSeparator and currently no IFormatProvider
is given it will take the current culture which is in your case german. So to solve this problem you should try the following code:
// Get a default DateTimeFormat
var dateTimeFormat = new CultureInfo("en-US").DateTimeFormat;
// Change the DateSeparator
dateTimeFormat.DateSeparator = "-";
// Output it as normal
var output = DateTime.Now.ToString(dateTimeFormat.ShortDatePattern, dateTimeFormat);
And with these informations you should also be able to make some assumptions about what is faster:
var output = DateTime.Now.ToString(dateTimeFormat.ShortDatePattern, dateTimeFormat);
var output = DateTime.Now.ToString("M/d/yyyy", dateTimeFormat);
Due to the fact that these are exactly the same there should be no difference in performance