首页 > 解决方案 > Powershell仅返回日出/日落时间

问题描述

我正在使用休息 API 返回我所在位置的日出和日落时间。

$Daylight = (Invoke-RestMethod "https://api.sunrise-sunset.org/json?lat=35.608237&lng=-78.647497").results
$Sunrise  = ($Daylight.Sunrise | Get-Date -Format HH:mm).ToLocalTime()
$Sunset  = ($Daylight.Sunset | Get-Date -Format HH:mm).ToLocalTime()

但是,需要对输出进行格式化以仅提供时间而不是完整日期。我试过添加-format hh:mm(如上所示),但它出错了:

Method invocation failed because [System.String] does not contain a method named 'ToLocalTime'.
At line:3 char:1
+ $Sunrise  = ($Daylight.Sunrise | Get-Date -Format HH:mm).ToLocalTime( ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

这样做的正确方法是什么?

标签: powershell

解决方案


根据API文档,您可以更改日期格式。通过使用formatted=0参数,Get-date 将为您提供您所在时区的实际时间。

$Daylight = (Invoke-RestMethod "https://api.sunrise-sunset.org/json?lat=35.608237&lng=-78.647497&formatted=0").results
$Sunrise  = ($Daylight.Sunrise | Get-Date -Format "HH:mm")
$Sunset   = ($Daylight.Sunset | Get-Date -Format "HH:mm")

编辑昨天的日落:

如果你想要昨天的日落,你可以向 Rest API 询问一个具体的日期:

$Yesterday = (Get-Date).AddDays(-1) | Get-Date -Format "yyyy-MM-dd"
$Daylight = (Invoke-RestMethod "https://api.sunrise-sunset.org/json?lat=35.608237&lng=-78.647497&formatted=0&date=$Yesterday").results
$Sunrise  = ($Daylight.Sunrise | Get-Date -Format "HH:mm")
$Sunset   = ($Daylight.Sunset | Get-Date -Format "HH:mm")

推荐阅读