- Perl 6 Deep Dive
- Andrew Shitov
- 396字
- 2021-07-03 00:05:54
Using the Date class
The Date class represents the date—a collection of three numbers, year, month, and a day of the month. To create a new date, call a constructor with the three values:
my $date = Date.new(2017, 7, 19);
say $date; # 2017-07-19
To create a variable based on today's date, use the today method, as follows:
my $today = Date.today;
say $today; # 2017-07-17
To clone a date, call clone, as follows:
my $date2 = $today.clone;
Separate parts of the date are available from the clearly-named methods of the date, as follows:
say $date.year; # 2017
say $date.month; # 7
say $date.day; # 19
Additionally (and this is already a nice bonus), the Date class can calculate the day of the week (Monday is 1, Sunday is 7):
say $date.day-of-week; # 3 (Wednesday)
There are also the day-of-month and day-of-year methods:
say $date.day-of-month; # 19 (same as $date.day)
say $date.day-of-year; # 20
A few methods help with counting weeks:
say $date.week; # (2017 29)
say $date.week-number; # 29
say $date.week-year; # 2017
For the weeks in January, the year returned by the week and week-year methods may either be the previous or the next year, depending on which week the day belongs to. For example, take the last day of 2019 and the first day of 2020. 31st December, 2019 is a Tuesday and 1st January, 2020 is a Wednesday. Both days belong to the same week, so the week-year method returns 2020. Examine the output of the following program to understand how the method works:
my $d1 = Date.new(2019, 12, 31);
say $d1.day-of-week; # 3
say $d1.year; # 2019
say $d1.week-year; # 2020
my $d2 = Date.new(2020, 1, 1);
say $d2.day-of-week; # 4
say $d2.year; # 2020
say $d2.week-year; # 2020
There's an interesting weekday-of-month method that returns the number of occurrences of this day of the week in this month before the given date. For example, 19 July, 2017 is the third Wednesday in July 2017:
say $date.weekday-of-month; # 3
Date calculations are very easy with the help of the earlier and later methods:
say $today.later(days => 2); # 2017-07-19
say $today.later(months => 2); # 2017-07-21
To get yesterday's and tomorrow's date, use the pred and succ methods, which we have already seen in the numeric data types:
say $today.pred; # 2017-07-18
say $today.succ; # 2017-07-20
- 編程的修煉
- Java高手真經(jīng)(高級(jí)編程卷):Java Web高級(jí)開發(fā)技術(shù)
- Java Web程序設(shè)計(jì)
- 實(shí)戰(zhàn)低代碼
- SEO實(shí)戰(zhàn)密碼
- 名師講壇:Spring實(shí)戰(zhàn)開發(fā)(Redis+SpringDataJPA+SpringMVC+SpringSecurity)
- Windows Server 2016 Automation with PowerShell Cookbook(Second Edition)
- 用戶體驗(yàn)增長:數(shù)字化·智能化·綠色化
- Windows Phone 7.5:Building Location-aware Applications
- Mastering Business Intelligence with MicroStrategy
- Mastering openFrameworks:Creative Coding Demystified
- C語言程序設(shè)計(jì)
- SSM開發(fā)實(shí)戰(zhàn)教程(Spring+Spring MVC+MyBatis)
- App Inventor創(chuàng)意趣味編程進(jìn)階
- HTML5開發(fā)精要與實(shí)例詳解