Powershell: Get-Date -FromUnixTime should support negative values.

Created on 17 Jun 2020  路  6Comments  路  Source: PowerShell/PowerShell

Summary of the new feature/enhancement

PR #12179 added FromUnixTime parameter to the Get-Date command.
In PowerShell 7.1.0-preview.3, the following command causes an error.

PS /> Get-Date -Date -1 -FromUnixTime
Get-Date: Cannot bind parameter 'Date'. Cannot convert value "-1" to type "System. DateTime". Error: "String '-1' was not recognized as a valid DateTime."

This command should support negative unix time.

On Ubuntu, the following commands will not return an error.

$ date --date "@-1"
Wed Dec 31 23:59:59 UTC 1969

Proposed technical implementation details (optional)

The Date parameter of the Get-Date command has type DateTime. If an integer value is passed for this parameter, it will be interpreted as Ticks. This must be a positive value.

In other words, the following code is invalid.

PS /> [datetime] -1
InvalidArgument: Cannot convert value "-1" to type "System.DateTime". Error: "Ticks must be between DateTime.MinValue.Ticks and DateTime.MaxValue.Ticks. (Parameter 'ticks')"

Unix time can take a negative value, meaning that it is before Unix Epoch.

To allow the Date parameter to take a negative integer value, the type of this parameter must be changed to long.
But this is a breaking change.

I think the FromUnixTime parameter should be able to take a value, as was suggested in #11719.

Area-Cmdlets-Utility Issue-Question Resolution-Fixed

Most helpful comment

Rather than take the value in from -Date it almost seems better to just split the parameter set, and have -FromUnixTime take a value rather than be a switch parameter. 馃

All 6 comments

We need to see real scenarios where the feature could be useful.

Rather than take the value in from -Date it almost seems better to just split the parameter set, and have -FromUnixTime take a value rather than be a switch parameter. 馃

@vexx32 Agreed. BTW that's how I assumed it worked. Because of positional binding, it "appears" to work that way:

PS. get-date -FromUnixTime 1242342344

Thursday, May 14, 2009 11:05:44 PM

What is a type of the parameter? Signed long?

Yeah, I think that makes the most sense. That does appear to have been the original proposal, too, but that didn't carry through to the initial implementation, it seems.

:tada:This issue was addressed in #13084, which has now been successfully released as v7.1.0-preview.6.:tada:

Handy links:

Was this page helpful?
0 / 5 - 0 ratings