1

嗨,我有一个以下格式的字符串,23/03/2014 我尝试将其转换为这种格式:

string npacked = Convert.ToDateTime(packeddate).ToString("yyyy/MM/dd");

但我收到一个错误:

字符串未被识别为有效的 DateTime

也试过这个:

string npacked = DateTime.Parse(packeddate).ToString("yyyy/MM/dd");

但同样的错误。

4

4 回答 4

2

尝试使用ParseExact格式

string npacked = DateTime.ParseExact(packeddate, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy/MM/dd"); 

演示

于 2014-03-23T06:32:00.370 回答
1

Convert.ToDateTime 在您的字符串上运行 DateTime.Parse() (23/03/2014)。在将失败的默认文化 (en-US) 中,因为该文化中的日期应格式化为 MM/DD/YYYY。您需要根据MSDN切换到不同的文化(如法语) :

  // Reverse month and day to conform to the fr-FR culture. 
  // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
  dateString = "16/02/2008 12:15:12";
  try {
     dateValue = DateTime.Parse(dateString);
     Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
  }   
  catch (FormatException) {
     Console.WriteLine("Unable to convert '{0}'.", dateString);
  }

  // Call another overload of Parse to successfully convert string 
  // formatted according to conventions of fr-FR culture.       
  try {
     dateValue = DateTime.Parse(dateString, new CultureInfo("fr-FR", false));
     Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
  }   
  catch (FormatException) {
     Console.WriteLine("Unable to convert '{0}'.", dateString);
  }

之后调用“ToString”对解析尝试没有任何影响,它只是格式化解析的输出。

于 2014-03-23T06:35:58.373 回答
0

这可能是由于您的系统日期时间格式。您的系统中有mm-dd-yyyy格式,并且您正在尝试以dd-mm-yyyy格式解析它。尝试将系统日期格式更改为dd/MM/yyyy.

于 2014-03-23T06:41:29.530 回答
0

Convert.ToDateTime(string)显式调用DateTime.Parse(string, CultureInfo.CurrentCulture)。这意味着你的两条线是等价的。

在您的个人资料中,它说您来自阿拉伯联合酋长国的迪拜。这就是为什么我首先假设你CurrentCulture的可能是ar-AE,但你的字符串匹配它ShortDatePattern,这就是它打印的原因;

Convert.ToDateTime("23/03/2014", new CultureInfo("ar-AE")) // 23/03/2014

但是您没有告诉我们您的 是什么CurrentCulture,我们永远不知道.. 但是看起来您当前文化的日期分隔符不是/,或者您当前的文化没有标准日期格式dd/MM/yyyy(这对于大多数文化来说不太可能)您的两条线都失败了(第一种情况更有可能)。

/您可以使用具有DateSeparatorusingDateTime.ParseExact方法的区域性轻松解析字符串。此方法让您指定自定义日期格式。我们可以使用InvariantCulture例如;

var date = DateTime.ParseExact("23/03/2014",
                               "dd/MM/yyyy",
                               CultureInfo.InvariantCulture);

现在,让我们考虑一下它的yyyy/MM/dd格式表示。

/说明符在自定义日期格式中具有“用当前区域性的日期分隔符替换我”的特殊含义。这意味着如果您的日期分隔符不是/(我认为不是),您的date.ToString("yyyy/MM/dd")结果将包含在您的日期分隔符中,而不是/.

例如,我来自土耳其,我的文化是tr-TR. 我的日期分隔符是.(点)这就是这个例子的原因;

date.ToString("yyyy/MM/dd"); // Prints 2014.03.23 not 2014/03/23 

在这种情况下,您可以使用具有/日期分隔符的区域性作为ToString方法中的第二个参数(InvariantCulture例如),例如;

date.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture) // Prints 2014/03/23 

或者你可以逃避你的/角色,不管你喜欢哪种文化;

date.ToString(@"yyyy\/MM\/dd") // Prints 2014/03/23 
于 2014-03-23T08:21:07.467 回答