在Powershell中确定不同时区的夏令时状态

时间:2017-06-27 13:16:58

标签: powershell datetime timezone

在PowerShell中是否有一种灵巧的方式来确定另一个时区的过去日期是否为夏令时?这是情况,我们的数据库在欧洲,时间和日期是该服务器的本地。由于欧洲和美国在不同时间开始和停止夏令时,我需要考虑那些时间的小时差异。 谢谢你的建议。

3 个答案:

答案 0 :(得分:2)

无需尝试确定DST是否生效。只需让.NET Framework为您进行转换。

首先,确定要转换的时区ID。

你说你的输入时间是在欧洲,但你并没有详细说明。像美国一样Europe has multiple time zones。我假设你的意思是CET / CEST(UTC + 1 / + 2)。在Windows中,您可以使用以下任何标识符:

  • "Central Europe Standard Time"
  • "Central European Standard Time"
  • "Romance Standard Time"(为什么?谁知道。)
  • "W. Europe Standard Time"(不要被名字所迷惑,它仍然是中心)

除了显示名称外,它们都是相同的(在Windows中)。如果您想要精确选择哪一个,请参阅the CLDR reference

对于美国中部时区,请使用"Central Standard Time"

然后只需使用TimeZoneInfo.ConvertTimeBySystemTimeZoneId函数,如下所示:

# collect your input (through db, or whatever mechanism you have)
$inputDateTime = Get-Date -Date "2017-06-27 00:00:00"

# pick your time zones
$fromTimeZone = "Central Europe Standard Time"  # EU
$toTimeZone = "Central Standard Time"           # USA

# convert
$outputDateTime = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId(
  $inputDateTime, $fromTimeZone, $toTimeZone)

# output
Write-Output $outputDateTime

答案 1 :(得分:0)

我知道这是一个较旧的线程,但实际上我需要能够确定当前是否为DST。我们有一台服务器,其本地TZ设置为UTC(未显示DST),并且具有一个自动化功能,该功能需要能够知道本地时间是下午4点。因此脚本全部使用UTC,但是我可以根据此野兽结果的值添加一个小时或不添加一个小时:

$DST = ([System.TimeZoneInfo]::ConvertTimeFromUtc(
    (get-date).ToString(),
    [System.TimeZoneInfo]::FindSystemTimeZoneById("Central Standard Time")
)).isdaylightsavingtime()

答案 2 :(得分:0)

好,我很喜欢这个灵感,因为您的回应就像是扎了根草针,正是我所需要的。但是,它产生了一个错误。经过一番混乱后,我得到了以下工作:

$isDST = ([System.TimeZoneInfo]::ConvertTimeFromUtc((Get-Date).ToUniversalTime(), [System.TimeZoneInfo]::FindSystemTimeZoneById("Central Standard Time"))).IsDaylightSavingTime()

(在PowerShell v4中)