首页 > 开发 > PowerShell > 正文

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

2020-03-26 19:17:06
字体:
来源:转载
供稿:网友

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表