【问题标题】:To compare the day , date , timestamp of two lines in file and output the latest day,date,timestamp比较文件中两行的日期、日期、时间戳并输出最新的日期、日期、时间戳
【发布时间】:2019-12-24 06:50:42
【问题描述】:

我有来自两个不同文件的以下行,这些文件具有日期、日期、时间戳。我需要输出带有最新时间戳的行。

一个文件的行数:

Tue 31/12/2000 17:13:29.83 - file copied

另外一个文件内容是:

Sun 17/07/1996 12:11:14.84 - drivers updated

输出必须是

Tue 31/12/2000 17:13:29.83 - file copied

我们如何比较时间戳?

【问题讨论】:

  • 31/12/2000 是星期日,而不是星期二。 17/07/1996 是星期三,而不是星期日。这些错误是偶然的,还是文件中的真实内容?
  • @Theo,我们如何使用 3 个参数抑制“异常调用“Parseexact”:字符串未被识别为有效的日期时间”?
  • 这取决于您解析的日期是什么样的。您的两个示例前面的日期名称都错误,因此是我的评论,这就是我在回答中将其删除的原因。在这种情况下,您需要检查文件中的任何内容,以及它是否确实看起来是一个有效日期。

标签: powershell


【解决方案1】:

要从这些字符串中解析出日期,您可以这样做:

# get the date and time from the string, remove the dayname as it is incorrect for that date
$dateString = ("Sun 31/12/2000 17:13:29.83 - file copied" -split '-')[0].Substring(4).Trim()
$date1 = [datetime]::ParseExact($dateString, 'dd/MM/yyyy HH:mm:ss.ff', [CultureInfo]"en-US")

# do the same for the date in the second file and call that $date2

然后简单地使用比较日期

$theDateYouWant = if ($date1 -gt $date2) { $date1 } else { $date2 }

通过剥离日期名称,您可以使用$null[cultureinfo]::InvariantCulture 而不是[CultureInfo]"en-US"

【讨论】:

  • fwiw - this 很适合替换 if 语句:new DateTime(Math.Min(Date1.Ticks, Date2.Ticks))
  • @LievenKeersmaekers 是的,很好。在 PowerShell 语法中,这将是 $theDateYouWant = [datetime]([math]::Max($date1.Ticks, $date2.Ticks))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-19
相关资源
最近更新 更多