Reputation:
I wish to have a specific format for my DateTime depending on the current culture.
So I try this:
dateTime.ToString("dd/MM/yyyy hh:mm");
This is partially OK, the / gets replaced by the culture-specific separator. But the day and month order are not switched (like MM/dd) depending on the culture.
Using .ToString("g")
works, but that doesn't include the leading zero.
How do I accomplish this?
Upvotes: 2
Views: 19677
Reputation: 40527
try this:
var cinf = CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator;
DateTime.Now.ToString("dd/MM/yyyy hh:mm").Replace(cinf,"/");
Upvotes: 1
Reputation: 31071
If you are not happy with the standard patterns, you can edit them like this:
DateTimeFormatInfo format = (DateTimeFormatInfo) CultureInfo.CurrentCulture.DateTimeFormat.Clone();
format.ShortTimePattern = "hh:mm"; // example only
string result = value.ToString("g", format);
Upvotes: 0
Reputation: 158389
The /
character is a placeholder that will be replaced by the date separation character of the current culture. If you wish to "hard-code" the format to use /
you need to alter the format string like this:
dateTime.ToString("dd'/'MM'/'yyyy hh':'mm");
Upvotes: 2
Reputation: 19214
You do want to use "g", however the leading zero is dependant on the culture. The Invariant culture and some others will include the leading zero, but other cultures will not.
Any particular reason you want to maintain the leading zero?
Upvotes: 1
Reputation: 68506
I think this will do what you want:
System.Globalization.DateTimeFormatInfo format =
System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat;
string dateTime = DateTime.Now.ToString(format.FullDateTimePattern);
EDIT:
You can do the following for a short date/time:
System.Globalization.DateTimeFormatInfo format =
System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat;
string dateTime = DateTime.Now.ToString(format.ShortDatePattern + " " +
format.ShortTimePattern);
Upvotes: 11
Reputation: 84804
Instead of using "g", you might find the format you want in the Standard Date and Time Format Strings documentation page.
Edit: It looks like you may want CultureInfo.DateTimeFormat.ShortDatePattern, but check out the options anyway.
Upvotes: 4