C # datetime format
I want 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, // is replaced with a special delimiter. But the order of the day and month does not switch (like MM / dd) depending on the culture.
Usage .ToString("g")
works, but does not include leading zero.
How to do it?
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 in a short date / time:
System.Globalization.DateTimeFormatInfo format =
System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat;
string dateTime = DateTime.Now.ToString(format.ShortDatePattern + " " +
format.ShortTimePattern);
Instead of using "g", you can find the format you want on the Standard Date and Time Format documentation page .
Edit: It looks like you might want CultureInfo.DateTimeFormat.ShortDatePattern , but check the parameters anyway.
The character /
is a placeholder that will be replaced with the current culture date separator character. If you want to "hard-code" the format to use /
, you need to change the format string as follows:
dateTime.ToString("dd'/'MM'/'yyyy hh':'mm");
You want to use "g", but the leading zero is culture dependent. Invariant culture and some others will include a leading zero, but other cultures will not.
Any specific reason why you want to keep the leading zero?
try this:
var cinf = CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator;
DateTime.Now.ToString("dd/MM/yyyy hh:mm").Replace(cinf,"/");
This article should answer your question: Date and Time Formatting for a Specific Culture
If you are not satisfied with the standard templates, you can edit them as follows:
DateTimeFormatInfo format = (DateTimeFormatInfo) CultureInfo.CurrentCulture.DateTimeFormat.Clone();
format.ShortTimePattern = "hh:mm"; // example only
string result = value.ToString("g", format);