1

I have below lines from two different file having day , date ,timestamp. I need to output the line with latest timestamp.

The lines of one file :

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

And another file content is :

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

The output must be

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

How can we compare timestamp?

Hidei
  • 197
  • 4
  • 15
  • `31/12/2000` is a Sunday, not Tuesday. `17/07/1996` is a Wednesday, not Sunday. Are these mistakes by accident or is that the real content in the files? – Theo Dec 24 '19 at 07:41
  • @Theo, How can we suppress “ exception calling “”Parseexact”” with 3 arguments : string was not recognised as a valid Datetime”? – Hidei Dec 24 '19 at 13:27
  • That depends on what the date you are parsing looks like. Both your examples have the wrong day name in front, hence my comment and that is why I strip it off in my answer. In cases like that, you need to check whatever is in the file and if indeed it **looks like** a valid date. – Theo Dec 24 '19 at 14:22

1 Answers1

1

To parse out the date from these strings you can do:

# 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

Then simply compare the dates using

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

By stripping off the dayname, you can use $null or [cultureinfo]::InvariantCulture instead of [CultureInfo]"en-US"

Theo
  • 57,719
  • 8
  • 24
  • 41
  • fwiw - [this](https://stackoverflow.com/a/1985404/52598) is nice to replace the if statement: `new DateTime(Math.Min(Date1.Ticks, Date2.Ticks))` – Lieven Keersmaekers Dec 24 '19 at 08:59
  • 1
    @LievenKeersmaekers Yes, nice. In PowerShell syntax this would be `$theDateYouWant = [datetime]([math]::Max($date1.Ticks, $date2.Ticks))` – Theo Dec 24 '19 at 16:16