Date/Time to Epoch

Hi,

I’m trying to create a script that requires date/times in Epoch format but struggling to get the format correct.

Ultimate Goal
At script runtime
For purpose of this example, say the script runs at 10:15 am
Get epoch time for last hour (rounded) such as 09:00 (Expected result = 1636448400)
Get epoch time for current hour (rounded) such as 10:00 (Expected result = 1636452000)

I currently have the following which aims to get the time, rounded to the current hour which seems to work:

$dte = Get-Date -Format "dd/MM/yy HH:00:00"
$dte

Output = 09/11/21 10:00:00

However, next, i need to get the time, rounded to the last hour so i tried this:

$dte = (Get-Date -Format "dd/MM/yy HH:00:00").AddHours(-1)
$dte

Output ERROR = Method invocation failed because [System.String] does not contain a method named ‘AddHours’.

I understand this is due to it no longer being in a date format, most likely due to me setting “:00:00” but not sure the best way to do this.

My aim then was to convert the date/time to Epoch by calculating seconds from 01/01/1970 to $dte

I also suspect this isn’t the best method to convert to Epoch and maybe there is a more efficient way to get to this result?

Any help would be greatly appreciated.

Regards,
Jamie

Having spent a considerable amount of time on https://www.epochconverter.com/ i just scrolled down and saw they had examples for various languages, including PS so adding a slight modification for the minus 1 hour seems to have done the trick.

Their example:

[int][double]::Parse((Get-Date (get-date).touniversaltime() -UFormat %s))

My modified version

[int][double]::Parse((Get-Date (get-date (get-date).AddHours(-1)).touniversaltime() -UFormat %s))

Maybe a bit easier to read:

New-TimeSpan -Start ([DateTime]::UnixEpoch) -End (Get-Date -Format 'dd/MM/yy HH:00:00') | 
    Select -ExpandProperty TotalSeconds