From 46071b7ff9c1d8da8efdc0411a8e38ccc1f8a17a Mon Sep 17 00:00:00 2001 From: Jack Casey Date: Tue, 7 Apr 2020 13:25:03 -0700 Subject: [PATCH] Add `-FromUnixTime` to `Get-Date` to allow Unix time input (#12179) --- .../commands/utility/GetDateCommand.cs | 15 ++++++++++++++- .../Get-Date.Tests.ps1 | 9 +++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs index aefbed7dbe..4516568cc3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs @@ -40,6 +40,12 @@ namespace Microsoft.PowerShell.Commands } } + /// + /// Gets or sets whether to treat a numeric input as ticks, or unix time. + /// + [Parameter] + public SwitchParameter FromUnixTime; + private DateTime _date; private bool _dateSpecified; @@ -237,7 +243,14 @@ namespace Microsoft.PowerShell.Commands // use passed date object if specified if (_dateSpecified) { - dateToUse = Date; + if (FromUnixTime.IsPresent) + { + dateToUse = DateTimeOffset.FromUnixTimeSeconds(Date.Ticks).UtcDateTime; + } + else + { + dateToUse = Date; + } } // use passed year if specified diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Date.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Date.Tests.ps1 index cdbb750898..0cdc794921 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Date.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Date.Tests.ps1 @@ -192,6 +192,15 @@ Describe "Get-Date" -Tags "CI" { $timeDifference.Milliseconds | Should -BeLessThan 1 $timeDifference.Ticks | Should -BeLessThan 10000 } + + It "-FromUnixTime works" { + + # Test conversion of arbitrary date in Unix time: 2020-01-01​T00:00:00.000Z + Get-Date -Date 1577836800 -FromUnixTime | Should -Be (Get-Date -Date 637134336000000000 -AsUTC) + + # Test converstion of Unix time start date: 1970-01-01​T00:00:00.000Z + Get-Date -Date 0 -FromUnixTime | Should -Be (Get-Date -Date 621355968000000000 -AsUTC) + } } Describe "Get-Date -UFormat tests" -Tags "CI" {