.net 在 localhost 和 azure 网站之间吐出不同的日期格式

.net spitting out different date format between localhost and azure website

我有一个问题,当我 运行 来自 VS2013 的网络应用程序时,它给我一种日期格式,当我解决它部署在 Azure 上时,它给我一种完全不同的日期格式。

这是一个例子: 顶部:运行宁在 Azure 上;底部:运行宁从 VS 本地 http://i.stack.imgur.com/qGiZQ.jpg

在浏览器中使用加拿大 (en-CA) 文化时会发生这种情况。

在出现在 UI 上之前,它们作为字符串与所有其他数据一起传送到自定义元素属性中,然后由 jquery 解析。

模型中的相关代码如下所示:

dynamic dynEffectiveStartDate
if (blah blah) 
{
     dynEffectiveStartDate = object.EffectiveStartDate.Value.ToString("MM/dd/yyyy");
}
else
{
     dynEffectiveStartDate = DateTime.Today.ToString("MM/dd/yyyy");
}
var dataStruct = new
{
     StartDate = dynEffectiveStartDate,
     EndDate = dynEffectiveEndDate,
     SomeStuff = anotherImportantDataString,
     DataStore = someMoreImportantData
};
…
someObject.serializedData = javascriptserializer.Serialize(dataStruct);
…

稍后我在 UI 中使用 $.datepicker.parsedate("mm/dd/yy", value) 将当前值传递给适当的编辑器, 但它会崩溃,因为有破折号而不是斜线。通常我会使用 $.datepicker.setDefault($.datepicer.regional[cultureVariable]); 为用户格式化 UI 中的日期,然后使用("getDate") 和 $.datepicker.formatDate("mm/dd/yyyy") 在 post.[=13 之前将其记录回自定义属性时=]

所以即使浏览器为英国人或澳大利亚人显示 31/12/2014,我仍然 post 12/31/2014 回到我的控制器。

然而,en-CA 文化代码在本地做一件事,在远程做另一件事。据我所知,DateTime.Today.ToString("MM/dd/yyyy"); returns格式"MM-dd-yyyy",这很烦人,因为我需要解析稍后将其变成真正的约会。不知道如果有人在中国或其他任何地方使用该应用程序,它是否会开始吐出 "dd-mm-yyyy" 或 "yyyy/mm/dd"。

如何确保后端提供我告诉它的日期格式?

这里有很多我能想到的问题
1. DateTime.Now - 这将根据您将其部署到的位置为您提供不同的结果。要解决此问题,请将时区保存在代码中的某些资源文件或静态设置中,然后使用 DateTime.UtcNow.Add(*/the time zone difference*/)

2. 您应该使用 DateTime.ToString(string, culture) see here 的重载。这将使您的格式保持不变,无论文化是什么,因为现在您负责提供文化。所以现在你的代码应该看起来像 .ToString("dd/M/yyyy", CultureInfo.InvariantCulture)

3. 使用依赖文化的格式将数据发送到 json 中的 UI。 read this

4. 将依赖于文化的日期时间发送到 UI。只是建议我在我的项目中做的是我发送 UTC 时间(ISO 8601) to the UI where in js code it is easier to parse it and then change it according to the timezone of the browser. Without this i will have to guess the timezone of the user using the location from the IP address(totally not worth the effort). this you can do easily using only vanila js OR you can use some of the js library(one that i use is momentjs)

除了使用文化变体,你还可以像这样强制它

string.Format("{0}/{1}/{2}", dt.Month, dt.Day, dt.Year);