netcore liunx docker修改默认的Datetime format
一、问题 :core项目发布在liunx docker下,使用了ORM用拉姆达表达式来设置where条件,当条件中有datetime类型的时候默认生成出来的sql语句用的DateTime.ToString() 如下例
SELECT * FROM #table WHERE CreateTime >='01/01/2020 00:00:00'
这样执行mysql或者mssqlserver会报错,但又不方便改ORM底层的代码
二、解决办法:
在Startup.cs文件Configure中新增以下代码(在IIS下同样有效):
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//设置CultureInfo
var zh = new CultureInfo("zh-CN");
zh.DateTimeFormat.FullDateTimePattern = "yyyy-MM-dd HH:mm:ss";
zh.DateTimeFormat.LongDatePattern = "yyyy-MM-dd";
zh.DateTimeFormat.LongTimePattern = "HH:mm:ss";
zh.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
zh.DateTimeFormat.ShortTimePattern = "HH:mm:ss";
IList<CultureInfo> supportedCultures = new List<CultureInfo>
{
zh,
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("zh-CN"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
});
}
三、测试代码:
public IActionResult Test()
{
string date = DateTime.Now.ToString();
return Content(date);
}
输出结果: 2020-01-07 12:29:12
PS: 注意下docker里还需要设置好时区,方法自行搜索