2

First off, I'm not a coder by profession, just a lowly network engineer :) But I'm a big believer in automation and try to write scripts to handle tasks they're suited for

I'm attempting to get the current UNIX timestamp for 10 minutes ago in PowerShell, for use in a database-check script. I'm using this to get the current Unix-time:

$unixtime=[int][double]::Parse((Get-Date -UFormat %s))-600

But when I run it through a UNIX-time to local time converter (http://www.onlineconversion.com/unix_time.htm), I'm getting the current time in GMT (for example, if I run it right now I get "1340620608", which the converter says is 10:36 AM GMT, when the actual time is 10:36 AM CDT). This obviously causes issues when comparing to Unix timestamps in the database, as they are in local time. While I could write (or find) a function that would calculate the current GMT offset and apply it to my timestamp, I was wondering if there is a better way to go about this.

3 Answers 3

4

Try:

$unixtime=[int][double]::Parse($(Get-Date -date (Get-Date).ToUniversalTime()-uformat %s))

The above gets the current GMT time first then converts it to the correct format.

Sign up to request clarification or add additional context in comments.

2 Comments

Perfection! :) Thanks for this, it makes more sense now that I realized that the issue was the "pre-conversion" time was in local time.
You just need [long]($(Get-Date -date (Get-Date).ToUniversalTime()-uformat %s)). No need to parse like that. Besides you'll need [long] to avoid y2k38 issue anyway. Never use int
2

Does this work for you?

(Get-Date).AddMinutes(-10).Subtract((Get-Date 1/1/1970)).TotalSeconds

Comments

1

Unix timestamps are defined as seconds since 1970-01-01 00:00:00 GMT.

If the timestamps in your database are stored as seconds since 1970 local time, perhaps you need to fix your database. But it's likely that your database timestamps are standard UTC-based Unix timestamps.

You should also check your system's time and timezone settings; your computer may be treating GMT as local time (and its clock could be several hours off).

2 Comments

You're absolutely right, the stamps in the DB are in the proper Unix timestamp format. After reading Russellds' answer above I realized that the actual issue is, is that PowerShell is taking my local system time (which is in the correct Time Zone per the Control Panel) and converting it directly to "number of seconds since 1/1/70" without first changing local time to GMT. You then get a timestamp that is assumed to be in GMT but is not :)
@GregDickinson that's a bug in PowerShell 5.1. I've checked in PowerShell Core 7.x and see that it's been fixed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.