Creating a DateTime object with a specific UTC DateTime in PowerShell

痞子三分冷 提交于 2019-12-03 11:38:29

问题


I'm trying to create a DateTime object with a specific UTC timestamp in PowerShell. What's the simplest way to do this?

I tried:

Get-Date
    -Format (Get-Culture).DateTimeFormat.UniversalSortableDateTimePattern
    -Date "1970-01-01 00:00:00Z"

but I get this output:

1969-12-31 19:00:00Z

It's a few hours off. Where's my lapse in understanding?


回答1:


The DateTime object itself is being created with the proper UTC time. But when PowerShell prints it out it converts it to my local culture and time zone, thus the difference.

Proof:

$UtcTime = Get-Date -Date "1970-01-01 00:00:00Z"
$UtcTime.ToUniversalTime()



回答2:


(get-date).ToUniversalTime().ToString("yyyyMMddTHHmmssfffffffZ")



回答3:


$utctime = New-Object DateTime 1970, 1, 1, 0, 0, 0, ([DateTimeKind]::Utc)

If you print out $utctime, then you get:

1. januar 1970 00:00:00

Also, $utctime.Kind is correctly set to Utc.




回答4:


$time = [DateTime]::UtcNow | get-date -Format "yyyy-MM-ddTHH:mm:ssZ"

This appears to also work




回答5:


You can use the SpecifyKind method:

PS C:\IT\s3> $timestamp

Wednesday, July 18, 2018 7:57:14 PM

PS C:\IT\s3> $timestamp.kind

Unspecified

PS C:\IT\s3> $utctimestamp = [DateTime]::SpecifyKind($timestamp,[DateTimeKind]::Utc)

PS C:\IT\s3> $utctimestamp

Wednesday, July 18, 2018 7:57:14 PM

PS C:\IT\s3> $utctimestamp.kind

Utc




回答6:


This is how it works in .NET, right? PowerShell just calls the ToUniversalTime method. From http://msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx

The Coordinated Universal Time (UTC) is equal to the local time minus the 
UTC offset. For more information about the UTC offset, see TimeZone.GetUtcOffset.
The conversion also takes into account the daylight saving time rule that applies 
to the time represented by the current DateTime object. 


来源:https://stackoverflow.com/questions/10487011/creating-a-datetime-object-with-a-specific-utc-datetime-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!