whoisearth
whoisearth

Reputation: 4170

convert dd MMM yyyy to unix time

I have a string I'm pulling from a file in the format of dd MMM yyyy which I'd like to convert to unixtime to monitor on.

As an example:

19 Jul 2017

I want to display as:

1500422400

Per some searching I'm trying the following:

$dateValue = "19 Jul 2017"
$date1 = Get-Date -Date "01/01/1970"
$date2 = Get-Date -Date $dateValue
$unixtime = Get-Date (New-TimeSpan -Start $date1 -End $date2).TotalSeconds

I get the following error:

Get-Date : Cannot bind parameter 'Date'. Cannot convert value "1530662400" to type "System.DateTime". Error: "String was not recognized as a valid DateTime." At D:\cppib\bin\snlStatus.ps1:19 char:22 + $unixtime = Get-Date (New-TimeSpan -Start $date1 -End $date2).TotalSeconds + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Get-Date], ParameterBindingException + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetDateCommand

Upvotes: 1

Views: 248

Answers (2)

Nkosi
Nkosi

Reputation: 247591

Remove the Get-Date in list line as it is trying to convert the Timespan's total seconds into a DateTime.

$dateValue = "19 Jul 2017"
$unixtime = ((Get-Date $dateValue)-(Get-Date "01 JAN 1970")).TotalSeconds
Write-Host $unixtime

Further checks found this

$dateValue = "19 Jul 2017"
$unixtime = Get-Date $dateValue -UFormat %s
Write-Host $unixtime

which returned the same thing.

Source: Get-Date

Upvotes: 2

whoisearth
whoisearth

Reputation: 4170

$unixstart = Get-Date -Date "01/01/1970"
$date2 = Get-Date $dateValue

$unixtime = (New-TimeSpan -Start $unixstart -End $date2).TotalSeconds

Write-Host $unixtime

Upvotes: 1

Related Questions