LoginSignup
0
0

More than 5 years have passed since last update.

速習Perl6の日付型

Last updated at Posted at 2015-12-09

こんばんは :whale2:

Perl 6 Advent Calendar 2015の9日目です。

今回はDateDateTimeクラスをざっとながめてみたいと思います。

Dateクラス

use v6;

# 今日
say my $today = Date.today; #=> 2015-12-09

# 翌日
say $today.succ;            #=> 2015-12-10

# 前日
say $today.pred;            #=> 2015-12-08

# 年/月/日
say $today.year;            #=> 2015
say $today.month;           #=> 12
say $today.day;             #=> 9

# うるう年?
say $today.is-leap-year;    #=> False

# 月の何日目?
say $today.day-of-month;    #=> 9

# 何曜日?
say $today.day-of-week;     #=> 3

# 年の何日目か
say $today.day-of-year;     #=> 343

# 年の何週目か
say $today.week.[1];        #=> 50

# この月何日まであるか
say $today.days-in-month;   #=> 31

# 2015年のクリスマス
say my $christmas = Date.new(2015, 12, 25); #=> 2015-12-25

# クリスマスまで何日
say $christmas - $today;    #=> 16

# 元旦(こういう指定もできます)
say my $newyear = Date.new(year => 2016, month => 1, day => 1); #=> 2016-01-01

DateTimeクラス

以下、何故かrb(Ruby)を指定してソース貼り付けしてます1

use v6;

# タイムゾーン '+09:00' 設定
my $*TZ = + 9 * 60 * 60;

# 元旦
put my $newyear = DateTime.new(
  year   => 2016,
  month  => 1,
  day    => 1,
  hour   => 21,
  minute => 15,
  second => 59,
  ).local; #=> 2016-01-02T06:15:59+09:00

# 2015年のクリスマス
put my $christmas = DateTime.new(
  :year(2015),
  :month(12),
  :day(25),
  ).local; #=> 2015-12-25T09:00:00+09:00


# 今日
put my $today = DateTime.new( time ).local; #=> 2015-12-09T22:35:24+09:00

# 今
put $today.now;      #=> 2015-12-09T22:35:24+09:00

# 時/分/秒
put $today.hour;     #=> 22
put $today.minute;   #=> 35
put $today.second;   #=> 24

# タイムゾーン確認 32400 ( = 9 * 60 * 60 )
put $today.timezone; #=> 32400

# 前日
say $today.earlier(days => 1);   #=> 2015-12-08T22:35:24+09:00

# 翌日
say $today.later(days => 1);     #=> 2015-12-10T22:35:24+09:00

# 翌月
say $today.later(months => 1);   #=> 2016-01-09T22:35:24+09:00

# タイムスタンプ
say $today.posix;                #=> 1449668124

# 標準時だと
say $today.utc;                  #=> 2015-12-09T13:35:24Z

(おまけ)演算子オーバーロード

use v6;

# 2015年のクリスマス
say my $christmas = DateTime.new(
  :year(2015),
  :month(12),
  :day(25),
  ).local; #=> 2015-12-25T09:00:00+09:00

# 今日
say my $today = DateTime.new( time ).local; #=> 2015-12-09T22:35:24+09:00


## 演算子オーバーロード
# DateTime型同士で引き算して日付を返せるように
multi infix:«-»(DateTime $a, DateTime $b --> Int) {
  DateTime.new(($a.posix - $b.posix).Int, :timezone($a.timezone), :formatter($a.formatter)).day;
}

# クリスマスまで何日
say $christmas - $today; #=> 16

おわりです。

参考と注釈

0
0
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
0
0