【问题标题】:Extract the latest date time from a string从字符串中提取最新的日期时间
【发布时间】:2020-04-01 01:56:59
【问题描述】:

我有以下字符串格式的列值,例如:

第 1 行

PLX[12]@03/21 14:34 (475573-B) FCX[36]@03/22 17:03 (272497-B)LDX[44]@03/22 17:01 (272497-N)

第 2 行

PLX[12]@03/21 14:34 (475573-B)LDX[44]@03/22 17:01 (272497-N)

第 3 行

PLX[12]@03/21 14:34 (475573-B)

需要获取每一行的最新日期(03/22 17:03 for row1)并将其转换为DateTime

DateTime dt = DateTime.ParseExact("03/21 14:34", "MM/dd HH:mm", CultureInfo.InvariantCulture);

在从字符串中提取最新日期方面需要您的帮助。我不明白如何使用Regex 来让它工作。请推荐

【问题讨论】:

  • @JeremyThompson 这不是重复的!!我没有日期列表!我有一个包含许多日期的字符串
  • 为什么要使用正则表达式?似乎它是固定值字符串,因此string.Substring 将从该行中提取字符串日期表示。然后您可以将提取的字符串值转换为日期列表并找到最新的
  • @oleksa 在该字符串中的某个时间可以是 1 行,有时是 2 或 3 行,如问题中所示。我怎样才能使用子字符串呢?
  • 您需要做的是,对于每个字符串,使用 string.Substring 提取日期时间部分。然后使用 ParseExact 将每个子字符串转换为 DateTime。这会产生一个日期时间列表。然后使用标准方法从集合中查找最新的 DateTime。如果所有数据都在一个字符串中,请使用 String.Split 将其拆分为字符串数组
  • 1 个字符串包含PLX[12]@03/21 14:34 (475573-B) FCX[36]@03/22 17:03 (272497-B) LDX[44]@03/22 17:01 (272497-N) 如何获取最后一个?

标签: c# regex datetime


【解决方案1】:

这样解决

private static DateTime ParseDateTime(string dateTimeStr)
{
      var records = dateTimeStr.Split("\r\n");

      // example PLX[12]@03/21 14:34 (475573-B)            
       return records
          .Select(x => DateTime.ParseExact(x.Substring(8, 11), "MM/dd HH:mm", CultureInfo.InvariantCulture))
          .Max();
 }

感谢@oleksa 的建议

【讨论】:

    猜你喜欢
    • 2020-08-14
    • 2011-03-31
    • 1970-01-01
    • 2023-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 2023-03-18
    相关资源
    最近更新 更多