Windows command prompt showing incorrect time since epoch

61 views Asked by At

I am trying to monitor my app launch time on a Windows machine using command prompt. This is how I launch my electron app

powershell -command "(New-TimeSpan -Start (Get-Date "01/01/1970") -End (Get-Date)).TotalSeconds" & electron .

The time returned by command prompt looks hugely off. The following are values returned

  • command prompt - 1706093824 (sec)
  • electron app - 1706074025844 (msec)

In electron I am printing using

const now = Date.now(); // Unix timestamp in milliseconds
console.log( now );

Why is command prompt returning incorrect time? Can someone please suggest what am I doing wrong here?

2

There are 2 answers

0
window_handle On

As pointed out by @Stitt the time difference was due to local time zone. Subtracting it gave correct results.

0
phuclv On

Get-Date returns the local time, therefore Get-Date "01/01/1970" is the 01/01/1970 in your timezone, not the Unix Epoch timezone.

Your method to get Unix time is completely wrong. In PowerShell Core just use this

Get-Date -UFormat %s

And in older PowerShell due to a bug in -UFormat %s then you'll need to use either of the below

(Get-Date).ToUniversalTime() | Get-Date -UFormat %s
Get-Date -date (Get-Date).ToUniversalTime() -UFormat %s

It'll return the correct Unix Time from the exact Unix Epoch in UTC

%s: Seconds elapsed since January 1, 1970 00:00:00 (UTC)

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-date?view=powershell-7.3