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

标签 c# c#-4.0

我收到此错误“String was not recognized as a valid DateTime”,代码如下:

DateTimeOffSet dt=new DateTimeOffset(Convert.ToDateTime(DateTime.Now.ToString("dd/MM/yyyy hh:mm tt")));

它在开发环境中有效,但在生产环境中无效。

谁能告诉我上面的代码有什么问题吗?

谢谢。

最佳答案

Convert.ToDateTime 使用有关 DateTime 格式的当前文化信息。 尝试这样的事情:

string format = "dd/MM/yyyy hh:mm tt";
string stringDate = DateTime.Now.ToString(format, CultureInfo.InvariantCulture);
DateTime dateTime = DateTime.ParseExact(stringDate, format, CultureInfo.InvariantCulture);

关于c# - 字符串未被识别为有效的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6337680/

相关文章:

c# - 从同一类的实例自动更新现有的类属性

c# - 与 ListView、UserControl、DependencyProperty、ObservableCollection、INotifyPropertyChanged 的​​绑定(bind)错误

c# - 客户关系管理 2013 : Getting Data from Organization Service with Microsoft. XRM

c# - 如何将额外的属性字段添加到 asp.net 下拉列表中

c# - 指定编码 XmlSerializer

asp.net - 如何通过 System.Web.UI.DataVisualization.Chart 使用透明度

c# - 在 WCF 服务中将委托(delegate)人从客户端获取到服务器

c# - .NET Designer 中的 "could not find type System.Collections.Generic.List"是什么?

c# - C#在系统控制中启用音频设置 “listen to this device”

c# - 查找 int[] 中的所有连续数字