c# - 迁移到生产环境时出现日期时间问题

标签 c# datetime azure globalization typeconverter

我的 MVC 应用程序中有多个表单,其中的日期值是通过日期选择器工具选择的。这在本地调试时效果很好,但在部署到云环境时我的日期没有正确转换。我有以下代码:

string[] uploaddate = form.GetValues("uploaddate");
string[] expirydate = form.GetValues("expirydate");

这得到的日期为 31/08/2013 等,从这里我将转换为 DateTime,如下所示:

Convert.ToDateTime(uploaddate[0]);
Convert.ToDateTime(expirydate[0]);

当我部署到 Azure 服务器时,我收到以下错误:

字符串未被识别为有效的日期时间。

我认为实例镜像具有美国文化,而我的应用程序是按照英国格式设计的。如何解决这个问题,以便无论用户的文化如何,信息都会保存到数据库中?

最佳答案

你应该使用DateTime.TryParseExact 。您可以指定所有可能的格式,也不会抛出异常。

来自 MSDN 的示例。

string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                   "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                   "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                   "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                   "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", 
                        "5/1/2009 6:32:00", "05/01/2009 06:32", 
                        "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"}; 
DateTime dateValue;

foreach (string dateString in dateStrings)
{
   if (DateTime.TryParseExact(dateString, formats, 
                              new CultureInfo("en-US"), 
                              DateTimeStyles.None, 
                              out dateValue))
      Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
   else
      Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}

关于c# - 迁移到生产环境时出现日期时间问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18494124/

相关文章:

c# - 将托管事件处理程序传递给 Linux 中的非托管代码

javascript - 如何根据 php 返回的日期对象在 jquery 中创建一个新的日期对象?

c# - 将日期转换为日期时间格式c#

Windows Azure ACS 更改生产部署的联合元数据和 Web.Config

azure - 云项目iis express 8静态压缩被禁用

c# - Azure 表助手检查保存的项目是新的还是旧的

c# - C# 类中的父子关系

c# - 获取没有版本和其他详细信息的程序集名称

c# 序列化模型到 objectContent

java - 在 Java 中根据周查找季度