c# datetime format

好久不见. 提交于 2021-02-19 06:38:27

问题


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?


回答1:


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);



回答2:


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.




回答3:


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");



回答4:


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?




回答5:


try this:

var cinf = CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator;

DateTime.Now.ToString("dd/MM/yyyy hh:mm").Replace(cinf,"/");



回答6:


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);


来源:https://stackoverflow.com/questions/1538537/c-sharp-datetime-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!