ASP.NET C#MVC – 直接在DB或Model上更改datetime的格式

我正在努力寻找一种简单的方法来改变我的Table字段的DateTime格式。

我有一个名为Article的模型,其中包含一个名为releaseDate的字段,它是一个DateTime

我设法通过转换来实现(视觉上)

Article.releaseDate.ToString("dd/MM/yy") 

但问题是,当我尝试使用此格式从创建操作提交日期时,它会返回错误,告知格式错误。

有什么简单的方法可以将默认值(“MM / dd / yy”)更改为(“dd / MM / yy”)

提前致谢

您可以通过包含逐页更改文化信息

 <%@ Page UICulture="en" Culture="en-GB" %> 

或通过添加到您的web.config在所有页面中全局

  

两者都会将DateTime模型绑定更改为dd / MM / yyyy,因此不需要进行转换。

有关更多信息,请参阅此问题

代码相当于

 CultureInfo.CurrentUICulture.DateTimeFormat = CultureInfo.CurrentCulture.DateTimeFormat = new CultureInfo( "en-GB", false ).DateTimeFormat; 

是的。 肯定是队友:)

尝试更改当前线程的文化。 默认情况下,它需要系统的操作系统。 但你可以覆盖它。

看一下这个…

 Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-GB"); 

这是一篇很好的post解释….

HTH。

你的问题在于,由于编译器在两种情况下只能看到two digits/two digits/two digits ,所以在尝试实际转换之前,它无法知道你想要day/month/year而不是month/day/year ,并注意到您的月份值>= 12

你可以通过在/上拆分日期来解决这个问题,并将“正确”顺序的参数输入编译器,如下所示:

 string[] dateParts = input.Split("/"); int day; int month; int year; // You could use a boolean variable here to double-check that all casts are successful Int32.TryParse(dateParts[0], out day); Int32.TryParse(dateParts[1], out month); Int32.TryParse(dateParts[2], out year); var output = new DateTime(year, month, day); 

如果你把它放在一个单独的函数中,你可以像这样使用它来支持这两种格式:

 DateTime releaseDate; try { // will throw exception if input is not in the default format releaseDate = new DateTime(input); } catch (InvalidFormatException ex) { releaseDate = GetDateTimeFromNonStandardInput(input); } catch { throw; // or do whatever error handling you feel like. } 

就个人而言,我将GetDateTimeFromNonStandardInput()作为DateTime类的扩展方法。