午時(shí)三刻已到,行刑,刀下留人,現(xiàn)在到底是不是午時(shí),能否讓PowerShell告訴我呢?
好的, 沒問題。從晚上23點(diǎn)到凌晨2點(diǎn)之間屬于子時(shí),每兩個(gè)小時(shí)一個(gè)時(shí)辰,依次為“子丑寅卯辰巳午未申酉戌亥”。
函數(shù)獲取當(dāng)前時(shí)辰
用PowerShell腳本實(shí)現(xiàn):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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 ] + "時(shí)" } |
獲取當(dāng)前的時(shí)辰
PS> Get-Date
2014年9月17日 23:17:58
PS> Get-ChinaTimeAlias
子時(shí)
獲取指定小時(shí)數(shù)對應(yīng)的時(shí)辰
PS> Get-ChinaTimeAlias 12
午時(shí)
打印所有的時(shí)辰和對應(yīng)的時(shí)間段
輸入
1
2
3
4
5
6
7
8
9
10
11
|
$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]@{ 時(shí)辰 = $timeAlias; 時(shí)間段 = ( '{0}:00-{1}:59' -f $startHour,$endHour) } } |
輸出
時(shí)辰 時(shí)間段
-- ---
子時(shí) 23:00-00:59
丑時(shí) 01:00-02:59
寅時(shí) 03:00-04:59
卯時(shí) 05:00-06:59
辰時(shí) 07:00-08:59
巳時(shí) 09:00-10:59
午時(shí) 11:00-12:59
未時(shí) 13:00-14:59
申時(shí) 15:00-16:59
酉時(shí) 17:00-18:59
戌時(shí) 19:00-20:59
亥時(shí) 21:00-22:59
總結(jié)
字符串本身就是字符數(shù)組,沒必要把子丑寅卯等單獨(dú)保存成數(shù)組。
用求模和22特殊處理有效規(guī)避 對每一個(gè)時(shí)辰單獨(dú)條件判斷。