LoginSignup
6
7

More than 3 years have passed since last update.

PowerShellの日付操作

Last updated at Posted at 2020-12-14

はじめに

たまに使うと毎回調べているので、PowerShellの日時関連の処理をまとめます。
アドベントカレンダー遅刻してすみません。計画的に進めないとダメですね。

現在日時の取得

日付

Get-Date -DisplayHint Date
# -> 2020年12月2日

時刻

Get-Date -DisplayHint Time
# -> 18:03:58

日時

Get-Date -DisplayHint DateTime
# -> 2020年12月2日 18:04:33

文字列から日付を作成

ParseExact

基本構文

[DateTime]::ParseExact("変換する文字列","形式", $null);

サンプル

[DateTime]::ParseExact("20171231133355","yyyyMMddHHmmss", $null);
# -> 2017年12月31日 13:33:55

[DateTime]::ParseExact("171231133355","yyMMddHHmmss", $null);
# -> 2017年12月31日 13:33:55

指定した形式で表示

-Format

基本構文

Get-Date -Format "変換する形式"

サンプル

Get-Date -Format "yyyyMMddHHmmss"
# -> 20201214174433

$date = [DateTime]::ParseExact("20171231133355","yyyyMMddHHmmss", $null);
$date.ToString("yyyyMMdd")
# -> 20171231
$date.ToString("yyyy年MM月dd日 HH時mm分ss秒")
# -> 2017年12月31日 13時33分55秒

日付の加算・減算

サンプル

$date = [DateTime]::ParseExact("20170615133030","yyyyMMddHHmmss", $null);

$date.AddYears(2)
# -> 2019年6月15日 13:30:30

$date.AddYears(-2)
# -> 2015年6月15日 13:30:30

$date.AddMonths(2)
# -> 2017年8月15日 13:30:30

$date.AddMonths(-2)
# -> 2017年4月15日 13:30:30

$date.AddDays(5)
# -> 2017年6月20日 13:30:30

$date.AddDays(-4)
# -> 2017年6月11日 13:30:30

$date.AddHours(5)
# -> 2017年6月15日 18:30:30

$date.AddHours(-5)
# -> 2017年6月15日 8:30:30

$date.AddMinutes(5)
# -> 2017年6月15日 13:35:30

$date.AddMinutes(-5)
# -> 2017年6月15日 13:25:30

$date.Addseconds(5)
# -> 2017年6月15日 13:30:35

$date.Addseconds(-5)
# -> 2017年6月15日 13:30:25

2つの日付の差

日付同士を引くといろいろな形式で確認できる。

$date1 = [DateTime]::ParseExact("20170615133030","yyyyMMddHHmmss", $null);
$date2 = [DateTime]::ParseExact("20201102095548","yyyyMMddHHmmss", $null);
$date2 - $date1

Days              : 1235
Hours             : 20
Minutes           : 25
Seconds           : 18
Milliseconds      : 0
Ticks             : 1067775180000000
TotalDays         : 1235.85090277778
TotalHours        : 29660.4216666667
TotalMinutes      : 1779625.3
TotalSeconds      : 106777518
TotalMilliseconds : 106777518000

形式

項目 .NET UFormat
年(4桁) yyyy %Y
年(2桁) yy %y
MM %m
dd %d
時(24時間) HH %H
時(12時間) hh %h
mm %M
ss %S
曜日 dddd %B
タイムゾーン K

参考

PowerShell Core入門 - 基本コマンドの使い方 日付を表示 Get-Date
Get-Date

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7