华域联盟 PowerShell Powershell小技巧之获取当前的时间并转换为时辰

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

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

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » Powershell小技巧之获取当前的时间并转换为时辰

转载请保留出处和原文链接:https://www.cnhackhy.com/14525.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部