Home > Software design >  Extract time from date time and find difference between 2 times
Extract time from date time and find difference between 2 times

Time:10-13

I am trying to convert EPOC time to date time and need to extract the time only from that

I am doing below

 $min = $Time_Start | measure -Minimum
 $max = $Time_End | measure -Maximum
 [datetime]$oUNIXDatemin=(Get-Date 01.01.1970) ([System.TimeSpan]::fromseconds($min.Minimum))
 $oUNIXDatemin_1 = $oUNIXDatemin.ToString("HH:mm:ss")
 [datetime]$oUNIXDatemax=(Get-Date 01.01.1970) ([System.TimeSpan]::fromseconds($max.Maximum))
 $oUNIXDatemax_1 = $oUNIXDatemax.ToString("HH:mm:ss")

Problem is while converting I am getting $oUNIXDatemin_1 and $oUNIXDatemax_1 value like

$oUNIXDatemin_1

12 October 2021 07:46:46

$oUNIXDatemax_1

12 October 2021 21:16:04

My EPOC values are

$min.Minimum
1634024806

$max.Maximum
1634073364

Please let me know what is wrong here. Need to find the difference in HH:mm:ss format.

CodePudding user response:

In PowerShell, you'd usually use a format string. Subtracting two PowerShell datetimes returns a value of type Timespan, which is well-behaved over a span of more than 24 hours.

([datetime]"12 October 2021 21:16:04" - [datetime]"12 October 2021 07:46:46") -f "HH:mm:ss"
13:29:18

Be careful here. Both intervals (durations) and time (of day) have the same format, but different meanings. For example, it makes sense to multiply the interval "01:00:00" by 3 to get three hours; it doesn't make sense to multiply the time "01:00:00" (1 o'clock AM) by 3.

I'm sure the overall calculation can be simplified, but it's too early for me.

  • Related