C# 系统日期时间格式已更改

C# 系统日期时间格式已更改,c#,windows-7,datetime-format,C#,Windows 7,Datetime Format,我的计算机上安装了Windows7。问题是,如果计算机重新启动,系统日期格式会在某个时间发生更改。我需要确定日期格式,但不知道如何确定。我在mvc 3中构建了应用程序,并编写了从字符串到日期时间的转换代码。如果系统日期时间格式与字符串不匹配,则显示错误 字符串格式不正确无法转换为查找系统日期时间的日期时间。异常在以下代码中引发: DateTime startDate = Convert.ToDateTime(start); 在哪里, string start = sundayOfLastWe

我的计算机上安装了Windows7。问题是,如果计算机重新启动,系统日期格式会在某个时间发生更改。我需要确定日期格式,但不知道如何确定。我在mvc 3中构建了应用程序,并编写了从字符串到日期时间的转换代码。如果系统日期时间格式与字符串不匹配,则显示错误
字符串格式不正确
无法转换为查找系统日期时间的日期时间。异常在以下代码中引发:

 DateTime startDate = Convert.ToDateTime(start);
在哪里,

string start = sundayOfLastWeek.ToString("MM/dd/yyyy HH:mm:ss");
或者,是否有任何替代方案,以便我可以在不考虑系统日期时间的情况下更改始终有效的代码。

使用
“MM/dd/yyyy HH:MM:ss”格式。

编辑:基于@John Woo的评论

您可以将字符串数组传递给DateTime。解析方式如下:

string[] dateFormats = new string[] { "MM/dd/yyyy HH:mm:ss", "dd/MM/yyyy HH:mm:ss", "d/MM/yyyy" };
DateTime startDate = DateTime.ParseExact(start,
                                         dateFormats, 
                                         CultureInfo.InvariantCulture,
                                         DateTimeStyles.None);
与格式“MM/dd/yyyy HH:MM:ss”一起使用

编辑:基于@John Woo的评论

您可以将字符串数组传递给DateTime。解析方式如下:

string[] dateFormats = new string[] { "MM/dd/yyyy HH:mm:ss", "dd/MM/yyyy HH:mm:ss", "d/MM/yyyy" };
DateTime startDate = DateTime.ParseExact(start,
                                         dateFormats, 
                                         CultureInfo.InvariantCulture,
                                         DateTimeStyles.None);
使用.ToString(CultureInfo.InvariantCulture)和Parse(value,CultureInfo.InvariantCulture)实现值的持久性。仅当渲染值用于显示时,才忽略CultureInfo。对于某些特定的数据格式,可能存在特殊的格式规则-请遵循这些规则

要恢复数据,请使用ParseExact.

使用.ToString(CultureInfo.InvariantCulture)和Parse(value,CultureInfo.InvariantCulture)进行值持久化。仅当渲染值用于显示时,才忽略CultureInfo。对于某些特定的数据格式,可能存在特殊的格式规则-请遵循这些规则


要恢复数据,请使用ParseExact.

,因为Habib已经回答了:

//Add any format you want or expect
string[] formats = { "MM/dd/yyyy HH:mm:ss", "dd.MM.yyyy HH:mm:ss" };
DateTime startDate = DateTime.ParseExact(start, formats,
                System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);

这应该会有帮助。

因为哈比卜已经回答了:

//Add any format you want or expect
string[] formats = { "MM/dd/yyyy HH:mm:ss", "dd.MM.yyyy HH:mm:ss" };
DateTime startDate = DateTime.ParseExact(start, formats,
                System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);

这应该会有帮助。

先生,如果日期时间的格式不是
MM/dd/yyyy HH:MM:ss
?会发生什么?它将引发异常,以避免您可以在字符串数组中添加可能/预期的日期时间格式并将其传递给方法。它显示错误,说明ParseExact:对于有两个参数的方法没有重载。它有三个参数,最后一个参数是
CultureInfo.InvariantCulture
sir,如果日期时间的格式不是
MM/dd/yyyy HH:MM:ss
,该怎么办?会发生什么情况?它将引发异常,以避免您可以在字符串数组中添加可能/预期的日期时间格式并将其传递给方法。它显示错误,说明ParseExact:对于有两个参数的方法没有重载。它有三个参数,最后一个参数是
CultureInfo.InvariantCulture