PowerShell获取当前的时辰 2


午时三刻已到,行刑,刀下留人,现在到底是不是午时,能否让PowerShell告诉我呢?

好的, 没问题。从晚上23点到凌晨2之间属于子时,每两个小时一个时辰,依次为“子丑寅卯辰巳午未申酉戌亥”。

函数获取当前时辰

用PowerShell脚本实现:

function Get-ChinaTimeAlias
{
 param(
  [ValidateRange(0,23)] 
 [int]$Hour = (get-date).Hour
 )
 $timeAliasArray='子丑寅卯辰巳午未申酉戌亥'
 [int]$index=0
 if($hour -eq 22){ $index=11 }
 else{
  $index=[math]::Floor( ( $hour+1 ) % 23 / 2 )
 }
 return $timeAliasArray[ $index ] + "时"
}

获取当前的时辰

PS> Get-Date

2014年9月17日 23:17:58


PS> Get-ChinaTimeAlias
子时

获取指定小时数对应的时辰

PS> Get-ChinaTimeAlias 12
午时

打印所有的时辰和对应的时间段

输入

$timeArray=@(23)+0..22
for($i=0;$i -lt $timeArray.Length; $i=$i+2) 
{
 $startHour = $timeArray[$i].ToString().PadLeft(2,'0')
 $endHour = $timeArray[$i+1].ToString().PadLeft(2,'0')
 $timeAlias = Get-ChinaTimeAlias $timeArray[$i]
 [pscustomobject]@{
    时辰   = $timeAlias;
    时间段 = ('{0}:00-{1}:59' -f $startHour,$endHour)
    }
}

输出

时辰 时间段        
-- ---        
子时 23:00-00:59
丑时 01:00-02:59
寅时 03:00-04:59
卯时 05:00-06:59
辰时 07:00-08:59
巳时 09:00-10:59
午时 11:00-12:59
未时 13:00-14:59
申时 15:00-16:59
酉时 17:00-18:59
戌时 19:00-20:59
亥时 21:00-22:59

总结

  • 字符串本身就是字符数组,没必要把子丑寅卯等单独保存成数组。
  • 用求模和22特殊处理有效规避 对每一个时辰单独条件判断。
本文链接: https://www.pstips.net/get-chinatimealias.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

关于 Mooser Lee

我是一个Powershell的爱好者,创建了PowerShell中文博客,热衷于Powershell技术的搜集和分享。本站部分内容来源于互联网,不足之处敬请谅解,并欢迎您批评指正。

回复 荔非苔 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

2 条评论 “PowerShell获取当前的时辰