Getting Wrong DateTime Format

拈花ヽ惹草 提交于 2019-12-24 08:56:59

问题


I have this:

var dateString = string.Format("{0:dd/MM/yyyy}", date);

But dateString is 13.05.2011 instead of 13/05/2011. Can you help me?


回答1:


You could use DateTime.ToString with CultureInfo.InvariantCulture instead:

var dateString = date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

The reason why / is replaced with . is that / is a custom format specifier

The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfo.DateSeparator property of the current or specified culture.

So either use InvariantCulture which uses / as date separator or - more appropriate - escape this format specifier by embedding it within ':

var dateString = date.ToString("dd'/'MM'/'yyyy");

Why this is more appropriate? Because you can still apply the local culture, f.e. if you want to output the month names, but you force / as date separator anyway.




回答2:


// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2012 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2012 16:05:07" - german (de-DE)

so you have to change Culture from German to English!

you can write :

date.ToString(new CultureInfo("en-EN"));



回答3:


try this:

  var dateString = string.Format("{0:dd}/{0:MM}/{0:yyyy}", date);

Also check out Steve X's site for string formatting: http://blog.stevex.net/string-formatting-in-csharp/




回答4:


Simply try

var dateString = date.ToString("dd/MM/yyyy", new System.Globalization.CultureInfo("en-GB"));



回答5:


If you want to force the date separator regardless of culture you can escape it, like this:

var dateString = string.Format(@"{0:dd\/MM\/yyyy}", date);

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx




回答6:


It seems a date seperator problem. Use this;

String.Format("{0:d/M/yyyy}", date);

Check String Format DateTime and look at DateTimeFormatInfo.DateSeperator property.




回答7:


Try this:

var dateString = string.Format("{0:dd/MM/yyyy}", DateTime.Today, new System.Globalization.CultureInfo("en-GB"));


来源:https://stackoverflow.com/questions/13725575/getting-wrong-datetime-format

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