字符串到日期时间的转换问题

本文关键字:转换 问题 时间 日期 字符串 | 更新日期: 2023-09-27 17:52:16

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

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

但是我得到一个错误:

字符串未被识别为有效的日期时间

也试过这个:

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

字符串到日期时间的转换问题

尝试使用

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

转换。ToDateTime在你的字符串(23/03/2014)上运行一个DateTime.Parse()。在默认区域性(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"对解析尝试没有任何影响,它只是格式化解析的输出。

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

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(这对大多数文化来说不太可能),你的两行都失败了(第一种情况更有可能)。

您可以使用DateTime.ParseExact方法轻松解析具有/作为DateSeparator的区域性的字符串。该方法允许您指定自定义日期格式。例如,我们可以使用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