Format a datetime in PowerShell to JSON as \/Date(1411704000000)\/

前端 未结 3 1211
感动是毒
感动是毒 2020-12-31 18:49

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

3条回答
  •  执念已碎
    2020-12-31 19:08

    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.

提交回复
热议问题