【问题标题】:Convert.ToDateTime in C# behave different from one environment to anotherC# 中的 Convert.ToDateTime 的行为因环境而异
【发布时间】:2013-05-20 08:26:27
【问题描述】:

我在 C# 中有以下代码行:

DateTime dtReportDate = Convert.ToDateTime(_ReportDate);

_ReportDate 是一个字符串变量,它的值为:21/05/2013 (dd/MM/yyyy)。所以我尝试将该日期转换为 DateTime 变量并执行以下操作:

_ReportDate = string.Format("{0:yyyy/MM/dd}", dtReportDate) + " " + _ReportHour;

如您所见,我需要以如下格式连接日期和小时:yyyy/MM/dd HH:mm。

在本地运行这些代码行时,它可以正常工作。但是,当我将它放在开发服务器中时,它会引发以下错误:String was not known as a valid DateTime.

所以,我想问几个问题。此错误是否可能与服务器的任何配置有关?为什么 Convert.ToDateTime 在本地工作正常,但在服务器上却不行?

任何线索都可以

谢谢

【问题讨论】:

  • 传递一个CultureInfo
  • 嗨 Slaks。感谢您的快速回复。我应该在哪里传递 CultureInfo?目前要使用 Convert.ToDateTime?

标签: datetime


【解决方案1】:

我已经弄清楚如何执行以下代码行来解决这个问题:

//Attempts to Parse the Date using the format specified (the third parameter can also be null)
DateTime dtReportDate = DateTime.ParseExact(_ReportDate,"dd/MM/yyyy", CultureInfo.InvariantCulture);

希望这对其他人有所帮助

【讨论】:

  • 您也可以这样做:DateTime.Parse("05/02/2013", new CultureInfo("DE-de"))(返回“2/5/2013 12:00:00 AM”)以使用特定文化的格式,而无需指定格式本身。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-20
  • 2010-11-09
  • 2015-11-29
相关资源
最近更新 更多