简体   繁体   English

DateTime.ToString()无法按预期使用斜杠作为日期分隔符

[英]DateTime.ToString() does not work as expected with slash as date-separator

I want to convert the date time to "MM/dd/yyyy" and when i am converting to this format the date is getting like "xx-xx-xxxx". 我想将日期时间转换为“MM / dd / yyyy”,当我转换为此格式时,日期变得像“xx-xx-xxxx”。 I have written code like 我写的代码就像

  var format = "MM/dd/yyyy HH:mm";
  DateTime dt = DateTime.Now;
  var dateString = dt.toString(format); // the value i am getting is 05-28-2014 12:47 but i require the 'dateString' value to be `05/28/2014 12:53`. 

What is the issue with that. 这有什么问题。

Your currrent culture's date-separator seems to be - that's why you get it. 你的文化文化的日期分隔符似乎是-这就是你得到它的原因。 You have to specify InvariantCulture : 您必须指定InvariantCulture

string dateString = dt.toString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);  

See: The "/" 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 . 从当前或指定区域性的DateTimeFormatInfo.DateSeparator属性中检索适当的本地化日期分隔符。

Another way is to escape the / with \\ : 另一种方法是使用\\来逃避/

string dateString = dt.toString(@"MM\/dd\/yyyy HH\:mm");  

But in my opinion, if you already know the special meaning of / as "current culture's date-separator", it's better(in terms of readability) to use the correct CultureInfo (or InvariantCulture ) instead. 但在我看来,如果你已经知道/作为“当前文化的日期分隔符”的特殊含义,那么使用正确的CultureInfo (或InvariantCulture )会更好(就可读性而言)。

This depends on your current culture date-separator. 这取决于您当前的文化日期分隔符。 Try to include InvariantCulture as follows: 尝试包括InvariantCulture,如下所示:

var dateStringFormat= dt.toString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);  

来自@TimSchmelter的答案的另一种方法是转义特殊符号/:因此它们不被视为日期和时间分隔符。

var dateString = dt.toString(@"MM\/dd\/yyyy HH\:mm");

you will specified the format while converting date and time ie DateTime.Now.ToString("MM/dd/yyyy hh:mm ss tt") 您将在转换日期和时间时指定格式,即DateTime.Now.ToString(“MM / dd / yyyy hh:mm ss tt”)

for more ref. 更多参考。 http://msdn.microsoft.com/en-us/library/system.datetime.aspx http://msdn.microsoft.com/en-us/library/system.datetime.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM