您的位置:首页 > 运维架构 > Shell

Powershell小技巧之获取当前的时间并转换为时辰

2018-10-12 14:10 786 查看

午时三刻已到,行刑,刀下留人,现在到底是不是午时,能否让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特殊处理有效规避 对每一个时辰单独条件判断。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: