2012-09-07 59 views
0

我的电脑中安装了Window 7。问题是如果计算机重新启动,系统日期格式会有所改变。我需要修改日期格式,但不知道如何。我有应用程序内置mvc 3,并有字符串日期时间转换的代码。如果系统日期时间格式与字符串不匹配,则会显示错误 string is not in proper format转换为查找系统日期时间的日期时间。唯一的例外是抛出下面的代码:系统日期时间格式已更改

DateTime startDate = Convert.ToDateTime(start); 

其中,

string start = sundayOfLastWeek.ToString("MM/dd/yyyy HH:mm:ss"); 

或者,是否有任何的替代品,这样我可以在工作的所有的时间,尽管系统日期时间更改代码。

回答

1

使用。 ToString(CultureInfo.InvariantCulture)和Parse(value,CultureInfo.InvariantCulture)值为persistance。如果您为显示目的渲染值,则只需省略CultureInfo。对于某些特定的数据格式,可能存在特殊的格式规则 - 请遵循它们。

恢复您的数据使用ParseExact。

4

使用DateTime.ParseExact与格式"MM/dd/yyyy HH:mm:ss"

startDate = DateTime.ParseExact(start, 
           "MM/dd/yyyy HH:mm:ss", 
           CultureInfo.InvariantCulture); 

编辑:基于评论来自@约翰佑

可以传递字符串数组来DateTime.Parse像:

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); 
+0

先生,如果日期时间的格式不是'MM/dd/yyyy HH:mm:ss'?会发生什么? –

+1

它会抛出一个异常,以避免您可以在字符串数组中添加可能/预期的日期时间格式并将其传递给方法 – Habib

+0

它会显示错误说明ParseExact:对于具有两个参数的方法没有重载。 – CodeManiac

0

由于哈比卜已经回答:

//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); 

它应该帮助。