【问题标题】:How to match timestamps of different formats如何匹配不同格式的时间戳
【发布时间】:2015-08-17 15:43:39
【问题描述】:

我有两个存储时间戳的列表。但是两个列表中的格式不同,ListA 将其存储为07/27/2015 18:10:14,而 ListB 将其存储为12:33。我的目标是搜索两个列表并匹配时间戳并输出它们。通过相同的时间戳,我的意思是..

假设列表 A 和列表 B 具有以下元素...

List A:                 List B:
07/27/2015 18:10:14     18:11   
07/29/2015 18:20:45     18:20
07/29/2015 18:20:11     19:23
07/11/2015 18:21:23     20:45

请注意,ListB 不包含秒信息,但 List A 包含。我想要以下格式的输出:

07/29/2015 18:20:45     18:20
07/29/2015 18:20:11

目前,我可以执行搜索,但我的结果中只能包含 ListA 中的一个时间戳。我想包括所有。任何帮助将不胜感激!

我尝试过的如下:

 for (int i = 0; i < ListA.Count(); i++)
        {
            for (int j = 0; j < ListB.Count(); j++)
            {
                if (ListA[i].Substring[11,5] == ListB[j])
                {
                    Console.WriteLine("Match Found");
                }
            }
        }

编辑::

List A:                 List B:
07/27/2015 18:10:14     18:11   
07/29/2015 18:20:45     20:45
07/29/2015 18:20:11     19:23
07/11/2015 18:21:23     18:20

【问题讨论】:

    标签: c# list timestamp


    【解决方案1】:

    通过将它们解析回 DateTime 对象并从中获取小时和分钟,您可以准确地比较它们

    for (int i = 0; i < ListA.Count(); i++)
    {
        bool found = false;
    
        for (int j = 0; j < ListB.Count(); j++)
        {
            DateTime aItem = DateTime.ParseExact(ListA[i], "MM/dd/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
            DateTime bItem = DateTime.ParseExact(ListB[j], "HH:mm", System.Globalization.CultureInfo.InvariantCulture);
    
            if (aItem.ToString("HH:mm") == bItem.ToString("HH:mm"))
            {
                  if (!found)
                  {
                      Console.WriteLine("{0}    {1}", ListA[i], ListB[j]);
                      found = true;
                  }
                  else
                      Console.WriteLine(ListA[i]);
            }
        }
    }
    

    编辑:抱歉,我完全误读了您的问题

    【讨论】:

    • 这是否适用于时间未排列的数据?检查,编辑中的示例数据。谢谢
    • 应该可以。如果您按照您所说的格式创建2个字符串数组(ListA和ListB),您可以对其进行测试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多