I want to get the current date as a string in the following format:
\\/Date(1411762618805)\\/
I have been fighting with PowerShell and have trie
So, the wonderful thing about JSON dates is... nothing. They are evil, and deserve to be punished.
So, what is a JSON date? It is the number of milliseconds since Unix Epoc (Jan 1, 1970), well, UTC time that is. So, that's great and all, but how do we get that without using the ConvertTo-JSON cmdlet? Easiest way I know of is this:
[int64]([datetime]::UtcNow)-(get-date "1/1/1970").TotalMilliseconds
That will get you the current date and time formatted for JSON. If you want a specific date or date/time you could do it, but you have to adjust for time zone, which we can do, it just gets long:
$target = "2/2/2014 6:32 PM"
[int64]((get-date $target).addhours((([datetime]::UtcNow)-(get-date)).Hours)-(get-date "1/1/1970")).totalmilliseconds
1391391120000
That would be the kick-off time for the last Super Bowl.
I know this is old but Google led me here. I'm using Invoke-RestMethod to send/receive JSON data, including timestamps in the /Date(1411704000000)/ format. I managed to convert from PowerShell to JSON using the following:
[System.DateTime]$(Get-Date).DateTime
Example:
@{DateTime = [System.DateTime]$(Get-Date).DateTime} | ConvertTo-Json
Returns:
{
"DateTime": "\/Date(1484023637000)\/"
}
There are two problem properties here, DateTime and DisplayHint and both require a different solution. The DateTime property is a ScriptProperty attached by the extended type system, so it exists on all DateTime objects automatically. You can remove it from all DateTime objects in the current session via Remove-TypeData
Get-TypeData System.DateTime | Remove-TypeData
The DisplayHint property is a NoteProperty that is added by the Get-Date cmdlet. I know of no way to suppress this from serialization. You can remove it explicitly from the DateTime:
Get-Date | foreach { $_.PSObject.Properties.Remove("DisplayHint"); $_ } | ConvertTo-Json
which will output
"\/Date(1411846057456)\/"
This is current date and time, if you only want the date you can do this
Get-Date | select -ExpandProperty Date | ConvertTo-Json
Here we don't have to remove the DisplayHint because it was not attached by Get-Date.
Don't even get me started on the hoops you will have to jump through to convert back to the proper date time object.