Powershell小技巧之獲取當(dāng)前的時間并轉(zhuǎn)換為時辰
午時三刻已到,行刑,刀下留人,現(xiàn)在到底是不是午時,能否讓PowerShell告訴我呢?
好的, 沒問題。從晚上23點(diǎn)到凌晨2點(diǎn)之間屬于子時,每兩個小時一個時辰,依次為“子丑寅卯辰巳午未申酉戌亥”。
函數(shù)獲取當(dāng)前時辰
用PowerShell腳本實(shí)現(xiàn):
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 ] + "時" }
獲取當(dāng)前的時辰
PS> Get-Date
2014年9月17日 23:17:58
PS> Get-ChinaTimeAlias
子時
獲取指定小時數(shù)對應(yīng)的時辰
PS> Get-ChinaTimeAlias 12
午時
打印所有的時辰和對應(yīng)的時間段
輸入
$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
總結(jié)
字符串本身就是字符數(shù)組,沒必要把子丑寅卯等單獨(dú)保存成數(shù)組。
用求模和22特殊處理有效規(guī)避 對每一個時辰單獨(dú)條件判斷。
相關(guān)文章
探索PowerShell (二) PowerShell的基本操作
這里介紹下如何打開powershell控制臺,在 程序>附件>windows powershell中即可,主要是界面不再是dos窗口,據(jù)說功能也增加了很多2012-12-12Powershell腳本的4種執(zhí)行權(quán)限介紹
這篇文章主要介紹了Powershell腳本的4種執(zhí)行權(quán)限介紹,Windows默認(rèn)不允許任何腳本運(yùn)行,你可以使用"Set-ExecutionPolicy"cmdlet來改變的你PowerShell環(huán)境,共有4種運(yùn)行權(quán)限,需要的朋友可以參考下2015-06-06PowerShell入門教程之函數(shù)、腳本、作用域介紹
這篇文章主要介紹了PowerShell入門教程之函數(shù)、腳本、作用域介紹,本文所講內(nèi)容都是PowerShell的基礎(chǔ)知識,需要的朋友可以參考下2014-10-10PowerShell包含另一個腳本文件和獲取當(dāng)前腳本所在目錄的方法例子
這篇文章主要介紹了PowerShell包含另一個腳本文件和獲取當(dāng)前腳本所在目錄的方法例子,需要的朋友可以參考下2014-08-08PowerShell腳本實(shí)現(xiàn)添加、修改任務(wù)計劃的例子
這篇文章主要介紹了PowerShell腳本實(shí)現(xiàn)添加、修改任務(wù)計劃的例子,PowerShell操作、設(shè)置任務(wù)計劃實(shí)例,需要的朋友可以參考下2014-08-08Powershell小技巧之獲取當(dāng)前的時間并轉(zhuǎn)換為時辰
這篇文章主要介紹了使用Powershell獲取當(dāng)前的時間并轉(zhuǎn)換為時辰的方法,非常簡單實(shí)用,有需要的朋友可以參考下2014-09-09