【问题标题】:Convert different DateTime Strings to single DateTime format using C#使用 C# 将不同的 DateTime 字符串转换为单个 DateTime 格式
【发布时间】:2014-04-23 08:39:42
【问题描述】:

我创建了一个安装在所有主要浏览器中的浏览器扩展。安装完成后,我将从相关浏览器获取日期时间到我的应用程序,我的问题是不同浏览器的日期时间格式不同,如下所示

铬: 2014 年 4 月 10 日下午 1:06:49

Firefox 和 IE: 2014 年 4 月 10 日星期四下午 1:14:00

Safari: 2014 年 4 月 23 日星期三下午 14:00:17

我需要将所有不同的字符串格式日期时间转换为单一日期时间格式,目前我正在使用下面的代码,它适用于 chrome 日期时间格式,但不适用于其他格式

 public bool CompareInsertTimes(string strPluginDatetime)
    {
DateTime pluginModifyDate;            
 pluginModifyDate = DateTime.ParseExact(strPluginDatetime, "M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);

"strPluginDatetime" 是来自 chrome,firefox,IE,safari 的日期时间字符串 然后我使用以下格式将日期时间格式与我的数据库日期时间进行比较

Convert.ToDateTime(pluginModifyDate.GetDateTimeFormats()[28]) < Convert.ToDateTime(urlModifydateinDB.GetDateTimeFormats()[28])

那么,有没有可能将不同的字符串格式日期时间转换为单一日期时间格式

【问题讨论】:

  • 您是否查看过DateTime.ParseExact 的重载,它采用多种格式?你从哪里得到字符串?可能有更清洁的选择。
  • 您最好从源头获取正确格式的日期时间值。您的浏览器扩展程序不能以某种方式获取 ISO-8061 格式或 UNIX 时间戳的当前 UTC 日期/时间吗?
  • 那么,“4/10/2014 1:06:49 PM”是 10 月 4 日还是 4 月 10 日?这取决于你在哪里。除非您找到解决歧义的方法,否则这将是一项棘手的任务。
  • @spender:我没有看到“歧义”,因为 OP 已经提到他的代码适用于具有您的示例日期的 chrome。 OP 正在使用M/d/yyyy。所以恕我直言,很明显现在是 4 月 10 日,不是吗?
  • @TimSchmelter:我确信它“在他的机器上工作”;)

标签: c# datetime datetime-format


【解决方案1】:

这适用于所有人:

string[] dateStrings = { "4/10/2014 1:06:49 PM", "Thursday, April 10, 2014 1:14:00 PM", "Wednesday, April 23, 2014 14:00:17 PM"};
string[] formats = { "M/d/yyyy h:mm:ss tt", "dddd, MMMM dd, yyyy h:mm:ss tt", "dddd, MMMM dd, yyyy HH:mm:ss tt" };
DateTime[] dates = new DateTime[dateStrings.Length];
for(int i = 0; i < dateStrings.Length; i++)
{
    DateTime dt;
    bool ok = DateTime.TryParseExact(dateStrings[i], formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
    if (ok) dates[i] = dt;
}

测试:

Console.Write(string.Join(", ", dates));

输出:

10.04.2014 13:06:49, 10.04.2014 13:14:00, 23.04.2014 14:00:17

【讨论】:

  • 我不是 100% 相信 CultureInfo.InvariantCulture 是正确的:我没有检查过这一点,但希望浏览器使用当前用户的区域设置。无论如何,请确保您在不同文化的浏览器上进行测试。
  • 好点,那么 op 应该传递 null 或 CulturInfo.CurrentCulture。但是由于 op 也使用了 InvariantCulture 并且我不知道确切的日期是从哪里开始的,所以我保持原样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-12
  • 1970-01-01
  • 2017-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多