首页 > Web开发 > 详细

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

时间:2015-12-04 09:03:35      阅读:274      评论:0      收藏:0      [点我收藏+]

午时三刻已到,行刑,刀下留人,现在到底是不是午时,能否让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小技巧之获取当前的时间并转换为时辰

原文:http://www.jb51.net/article/55331.htm

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!