powershell - 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
这样做的正确方法是什么?
解决方案
根据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")
推荐阅读
- javascript - 如何在javascript中foreach一个数组或对象
- reactjs - 在本机中上传图像
- c - 来自 stdlib.h 的 qsort() 未对包含邮政编码和相应城市的指定结构进行排序
- javascript - Firestore 云函数递归更新子集合/集合组
- r - 在应用程序中的 if() 之后处理 NULL
- c# - 代理模式和存储库模式有什么区别
- excel - Excel:每个大陆的总人口总和(使用 Excel 公式 - 没有 Pivot)
- r - 在列之间重新排序个人 ID
- java - 为什么在 iText5 和 iText7 之间提取文本的位置不同?
- ssl - 为什么 OpenSSL 工具可以成功验证未签名的文件?