1. Perl
  2. Module
  3. here

DateTime - General - purpose handling of dates and times

DateTime gives you a general idea of dates and times.

So far, I've written articles trying to handle dates with standard modules, but it's not really a good idea. There are many exceptions to the date and time, and if you write its own script, bugs are likely to be mixed in.

This module is useful, but it relies on a large number of modules to handle dates generically. Also, some of them are written in C language to speed up the calculation of dates. For this reason, a little preparation is required for installation in a Windows environment.

For general information on dates and times, please refer to the following.

Install DateTime from CPAN

At the command prompt

cpan DateTime

Please hit. If you're new to cpan, you'll need to initialize the cpan settings (probably). If you are asked something, press Enter to proceed (very long).

If you've done the initial setup for cpan, you can download it. You will be asked many times if you want to install the dependent modules, so press ENTER to proceed.

If you proceed to the end, you are done.

Since Perl 5.10 and later, you can use Time::Piece as a standard Perl module, so it's a good idea to use Time::Piece. For the handling of time by Time::Piece, see "Handling date and time by" Time::Piece "".

DateTime initialization and acquisition of date/time information

To handle dates generically, use the DateTime module.

use DateTime;
my $dt = DateTime->new(
  year => 1964,
  month => 10,
  day => 16,
  hour => 16,
  minute => 12,
  second => 47,
);

The DateTime module is an object-oriented module. Create a DateTime object with the DateTime->new method. Specify the same number for the year and month.

You don't have to specify the year as a number from 1900 or the month as a number starting from 0, unlike the localtime function in the builtin functions or the Time::Local in the standard module.

Acquisition of date/time information

# Get method to get time information
my $year = $dt->year;
my $mon = $dt->month;
my $mday = $dt->day;
my $wday = $dt->day_of_week;
my $hour = $dt->hour;
my $minute = $dt->minute;
my $second = $dt->second;
my $yday = $dt->day_of_year;
my $qtr = $dt->quarter;

With the above method, you can get the date, hour, minute, second, day of the week, the number of days in a year, the number of counts in a quarter, and so on. Monday is 1 and Sunday is 7.

Get the current date and time

Use the now method to create a DateTime object that represents the current time. If you specify local for time_zone in the argument, it will be the time zone of your country that should be set in the OS.

my $dt = DateTime->now(time_zone =>'local');

You can also specify the time zone explicitly.

my $dt = DateTime->now(time_zone =>'Asia/Tokyo');

It seems that specifying the time zone explicitly is a little slower than specifying local. However, explicit specification impairs portability.

If no argument is specified, it will be UTC (Coordinated Universal Time).

my $dt = DateTime->now;

Create date information from epoch seconds

Use the from_epoch method to create a DateTime object from epoch seconds.

my $dt = DateTime->from_epoch(epoch => $epoch);

If you do not specify time_zone as an argument, it will be UTC (Coordinated Universal Time). You can get the local time by adding time_zone =>'local' as shown below.

my $dt = DateTime->from_epoch(epoch => $epoch, time_zone =>'local');

Create a timezone object

DateTime is a constructor that allows you to specify the time zone. You can reuse the DateTime::TimeZone object by creating it first.

my $time_zone = DateTime::TimeZone->new(name =>'Asia/Tokyo');

Creating a timezone object

Use the new method to create a timezone object. In the argument, specify the time zone name in name. (List of time zone names)

my $time_zone = DateTime::TimeZone->new(name =>'Asia/Tokyo');

Automatic generation of timezone objects

As shown below, if you specify the time zone in the DateTime constructor (new, now, etc.), the DateTime::TimeZone object is automatically created internally.

my $dt = DateTime->now(time_zone =>'Asia/Tokyo');

Every time you create a DateTime object, a DateTime::TimeZone object will be created.

This is a cost, so if you want to create a DateTime object more than once, it's a good idea to create a DateTime::TimeZone object first.

Use of timezone objects

Just specify the created DateTime::TimeZone object in time_zone, which is an argument of the DateTime constructor.

my $dt1 = DateTime->now(time_zone => $time_zone);

See "Time Zone List" for a list of time zones.

Specify the locale to output the month name and day of the week name in Japanese

The expression of the date differs depending on the country or region. For example, January is expressed as January in the United States. Monday is expressed as Monday. A set of expressions for each country or region is called a locale. The DateTime module allows you to specify locales for different countries and regions.

my $dt = DateTime->now(locale =>'ja');

The Japanese locale is ja.

Specifying the locale

The now method creates a DateTime object with current time information. You can specify locale as an argument.

Also, by specifying local for time_zone, time information is created at the local time.

my $dt = DateTime->now(locale =>'ja', time_zone =>'local');

Locale - dependent information Month name and day name

The following four methods depend on the locale. For example, day_name might be Monday if the locale is Japan, or Monday if the locale is somewhere in the Americas.

abbr is an abbreviation for abbreviation (abbreviation).

# Month name
my $month_name = $dt->month_name;

# Month abbreviation (same as month name if there is no abbreviation)
my $month_abbr = $dt->month_abbr;

# Day of the week name
my $day_name = $dt->day_name;

# Abbreviated name of the day of the week
my $day_abbr = $dt->day_abbr;

Encode for output

When you get the month name or day name, the characters used there are flagged as UTF-8. The fact that the UTF-8 flag is set means that Perl handles strings in an internal representation.

When outputting to a screen or file, it is necessary to turn off the UTF-8 flag. That is, you need to encode and convert the string from an internal representation to an external representation.

Windows people output in Shift-JIS, and other OS people output in UTF-8.

# Since the UTF-8 flag is set, encode it.
my $encode_to;
if ($^O eq 'MSWin32') {$encode_to = 'shift-jis'}
else {$encode_to = 'utf8'}
print(
  encode($encode_to, $month_name) . "\n".
  encode($encode_to, $month_abbr) . "\n".
  encode($encode_to, $day_name) . "\n".
  encode($encode_to, $day_abbr) . "\n"
);

Class for specifying locale

You can specify the locale name in the argument of the DateTime constructor.

my $locale = DateTime::Locale->load('ja');

DateTime creates a DateTime::Locale object in its constructor. Then, based on the generated locale object, it creates an output of date information for each region or country.

Explicit creation of locale object

my $locale = DateTime::Locale->load('ja');

To explicitly create a DateTime::Locale object, use the load method. The load method creates a DateTime::Locale object the first time, but reuses the DateTime::Locale object saved in memory from the second time onward.

There is always only one DateTime::Locale object that represents'ja' in your program. Such an object is called a singleton. It is not created every time like the DateTime::TimeZone object.

Pass the locale object to the constructor

To pass the locale object to the DateTime constructor:

my $dt = DateTime->now(locale => $locale, time_zone =>'local');

You can explicitly pass a locale object, but

my $dt = DateTime->now(locale =>'ja', time_zone =>'local');

It is easy to specify by a string like. If you write this, the DateTime::Locale object will be created automatically in the DateTime constructor.

See "List of available locales" for available locales.

Get all the date and time information

You can use DateTime to get date and time information. You can get it in various formats. You can specify the delimiter with the argument. If the argument is omitted, the date information is concatenated with-and the time information is concatenated with :.

# Date
# yyyy-mm-dd
my $ymd = $dt->ymd;

# yyyy/mm/dd
my $ymd_slash = $dt->ymd('/');

# mm-dd-yyyy
my $mdy = $dt->mdy;

# mm/dd/yyyy
my $mdy_slash = $dt->mdy('/');

# dd-mm-yyyy
my $dmy = $dt->dmy;

# dd/mm/yyyy
my $dmy_slash = $dt->dmy('/');

# Time information
# hh: mm: ss
my $hms = $dt->hms;

# hh-mm-ss
my $hms_hyphen = $dt->hms('-');

# Date and time information
my $ymdhms = $dt->datetime;

Output result

(1) Convenient output method of DateTime date/time
Date (hyphen) 2008-11-14
Date (slash) 2008/11/14
Month, day, year (hyphen) 11-14-2008
Month Day Year (Slash) 11/14/2008
Day Month Year (Hyphen) 14-11-2008
Day Month Year (Slash) 14/11/2008

Hour, minute and second (colon) 23:48:14
Hour, minute and second (hyphen) 23-48-14

Year, month, day, hour, minute, second 2008-11-14T23:48:14

Judgment of leap year Acquisition of the last day of the month

DateTime has a method to determine the leap year and a method to get the last day.

# Judge whether it is a leap year
my $is_leap_year = $dt1->is_leap_year;

# Last day of the month
my $dt2 = DateTime->last_day_of_month(year => 2008, month => 11);

Determine if it is a leap year.

Use the is_leap_year method to determine if it is a leap year.

my $is_leap_year = $dt1->is_leap_year;

Get the last day of the month

To get the last day of the month, use the last_day_of_month method. If you specify year and month as arguments, a DateTime object that represents the last day of the month is returned (not the last day of the month itself). Get the date from the returned DateTime object with the day method.

my $dt2 = DateTime->last_day_of_month(year => 2008, month => 11);

Date formatting "strftime" method

Use the strftime method to format the date. Pass the format specifier as an argument.

$dt->strftime("%a");

You can also specify multiple strings in combination as shown below.

$dt->strftime("%Y-%m-%d");

Strftime format specifier list

A list of strftime format specifiers.

%a Abbreviated name of the day of the week
%A Day of the week name
%b Month abbreviation
%B Month name
%c Default format
%C First two digits of the year
%d Day (01-31)
%D Same as%m /%d /%y. Month day year
%e Day (1 to 31): The second digit of the one-digit number (1 to 9) is a space.
%F Same as%Y-%m-%d (for example, 2008-11-31)
%G Year (I don't know the difference from%Y)
%g Last two digits of the year (00-99)
%h Same as%b. Month abbreviation
%H Hour (00 to 23)
%I Hours (01 to 12) Time in 12-hour notation
%j What day is it for the first time from the beginning of the year? (001 to 366)
%k Hour (0 to 23): The second digit of the one-digit number (0-9) is a space.
%l Hour (1 to 12) Time in 12-hour notation: The second digit of the one-digit number (0-9) is a space.
%m Month number (01-12)
%M Minutes (00 to 59)
%n Newline character
%N Milliseconds (%3N displays milliseconds in 3 digits,%6N displays milliseconds in 6 digits)
%p AM or PM
%P am or pm
%r Same as%I:%M:%S%p .. (11:55:23 PM etc.)
%R Hours and minutes (15:16, etc.)
%s Seconds from epoch
%S Seconds (00 to 61)
%t Tab character
%T Same as%H:%M:%S. Hours, minutes and seconds (such as 23:14:03)
%u Day of the week number (1 to 7. Monday is 1)
%U How many weeks have you counted from the beginning of the year? (00-53): Count the first Sunday of the year as the beginning of the week. The first Sunday week is 01. The week before that was 00.
%V How many weeks have you counted from the beginning of the year? (01-53): Let the week with at least 4 days be the first week of the year. Count Monday as the beginning of the week.
%w Day of the week number (0 to 6. Sunday is 0)
%W Weeks counting from the beginning of the year (00-53) Count the first Monday of the year as the beginning of the week. The first Monday week is 01. The week before that was 00.
%x Default format for dates
%X Default format for time
%y Last two digits of the year
%Y Year
%z Time zone time shift from UTC (Coordinated Universal Time))
%Z Time zone name
%% %%
%{method} You can use the methods of DateTime.pm. Example%{ymd}

Date addition

Use the add method to add dates and times.

# Addition of days
$dt->add(days => 1);

# Monthly addition
$dt->add(months => 1);

# Year addition
$dt->add(years => 1);

# Hour addition
$dt->add(hours => 1);

# Addition of minutes
$dt->add(minutes => 1);

# Addition of seconds
$dt->add(seconds => 1);

# Add all together
$dt->add(years => 1, months => 1, days => 1, hours => 1, minutes => 1, seconds => 1);

Date subtraction

Use the subtract method to subtract a period from a date.

# Subtraction of days
$dt->subtract(days => 1);

# Month subtraction
$dt->subtract(months => 1);

# Year subtraction
$dt->subtract(years => 1);

# Hour subtraction
$dt->subtract(hours => 1);

# Subtraction of minutes
$dt->subtract(minutes => 1);

# Second subtraction
$dt->subtract(seconds => 1);

You can also subtract dates. You can use the - symbol to make the calculation normal. (This is achieved using a feature called operator overloading.) The return value is a DateTime::Duration object that represents the period, not a DateTime object. You can get the date of the period with the years, months, days method.

my $duration = $dt2- $dt1;

There are two types of date subtraction. Some subtract the period on a date (for example, one month ago), while others subtract the dates (for example, the difference between October 10, 2008 and March 14, 2009).

Object representing the period

The period between dates is represented by the DateTime::Duration object. DateTime represents date information, while DateTime::Duration represents period information. When adding a certain period to a date or subtracting a certain period, I used the add method and the submit method, but internally, the operation is performed after the DateTime::Duration object is created.

When subtracting DateTime objects from each other, DateTime::Duration object is returned as a return value. A feature called operator overloading is used to allow subtraction between DateTime objects using the-symbol.

my $duration = $dt2- $dt1;

You can get the period information with the following method.

# Year
$duration->years;

# Month
$duration->months;

# Day 
$duration->days;

# Time
$duration->hours;

# Min
$duration->minutes;

# Seconds
$duration->seconds;

It's important to note that each method doesn't make sense on its own. For example, $duration->days does not represent the number of days in the period itself. If the duration is 1 month and 30 days, then $duration->months will be 1 and $duration->days will be 30.

The above method always returns a positive value, so it is not possible to determine which period comes first. Use the is_positive , is_zero , is_negative methods to determine the order of the periods.

# Date 2-Date 1 is positive
$duration->is_positive

# Date 2-Same date 1
$duration->is_zero

# Date 2-Date 1 is negative
$duration->is_negative

Use the in_units method to get the duration in certain units.

# 27 if the period is 1 year and 15 months
my $months = $duration->in_units('months');

# 2 if the period is 1 year and 15 months
my $years = $duration->in_inits('years');

# If the period is 1 year and 15 months, it will be (2, 3).
my ($years, $months) = $duration->in_units('years', 'months');

If you pass two arguments, you must receive them in list context.

Only the following four can be converted in units.

Year and month (1 year is 12 months)
Week and day (7 days a week)
Hours and minutes (1 hour is 60 minutes)
Seconds and milliseconds (1 second is 1000 milliseconds)

Days and months cannot be converted to each other. This is because the number of days varies from month to month.

It seems that minutes and seconds can be converted to each other, but they cannot. This is because the presence of leap seconds can make one minute 61 seconds.

Notes on date calculation

The date calculation has irregular parts, so it is better to use the simplest method possible. Here are some things to keep in mind about date calculations, including the causes that complicate date calculations.

Floating TimeZone

If the DateTime object is created with the new method and no time zone is specified, the default time zone will be what is called a floating time zone.

A floating time zone is a time zone that does not consider leap seconds and has nothing to do with any existing time zone.

If you don't need to consider the time zone and leap seconds, it's safest to calculate using the floating time zone.

For example, if you want to get the date from the log and get the date after 3 months, there is no problem in calculating in the floating time zone.

What is a leap second?

The time is not absolute, and the time when the rotation of the earth is one week is counted as one day, so if the rotation of the earth is delayed, the length of the day will change. Leap seconds are seconds that are inserted once every few years because the rotation of the earth is delayed year by year.

If you use a time zone that takes leap seconds into account and calculate the date so that the leap seconds are in between, there will be a one second difference from the case where the leap seconds are not in between.

What is daylight saving time?

Daylight saving time is a policy to advance the time by one hour for a certain period of the year. Because at a certain moment, the time is advanced by one hour.

, 1 hour time will be duplicated. If the normal time is 2 o'clock, it will be 1 o'clock immediately after changing the daylight saving time.

On this day, 1 o'clock and 2 o'clock overlap.

Therefore, in countries that have introduced daylight saving time, trying to calculate the time becomes very complicated.

In Japan, there is no daylight saving time, so there is no need to consider the effects of daylight saving time.

Convert a specific timezone to UTC

To simplify the date calculation, convert a specific time zone to UTC before calculating. Then, after the calculation is finished, return to the original time zone.

my $dt = DateTime->new(%user_input, time_zone => $user_tz);

# Convert to UTC
$dt->set_time_zone('UTC');

# Calculate the date.
# Return to the original time zone.
$dt->set_time_zone($user_tz);
print $dt->datetime;

In Japan, there is no daylight saving time, so even if you calculate with local time, you will not get strange results. It seems that there are quite a few countries in the world that have introduced daylight saving time.

Calculation in a specific time zone

Calculations in a particular time zone usually return correct results. However, if daylight savings time is in place and includes the time zone of the change to daylight savings time, weird results will be returned.

As explained above, it is safe to convert to UTC, calculate and then undo.

The default timezone for the now method

You can get the current time with the now method, but the default timezone is UTC.

If you create a DateTime object with new, the default timezone will be the floating timezone.

How to get the previous month and the next month

How to get the previous month and the next month using DateTime. (But I'm a little unsure)

# Current year and month
my $current_dt = DateTime->now(time_zone =>'local');
  
# Previous month
my $prev_dt = $current_dt->clone->add(months => -1, end_of_month =>'limit');

# Next month
my $next_dt = $current_dt->clone->add(months => 1, end_of_month =>'limit');

With the "end_of_month =>'limit'" option, I feel that the date can be obtained correctly even if the date is 1/31. For example, the result of adding January to 1/31 is 2/28.

I think that it is convenient for applications that want to transition pages to the previous month or the next month.

Example code

Finally, I will post the example code.

This is an example using DateTime.

use strict;
use warnings;
use DateTime;

# Initialization of DateTime object
# (Use the same year, not the year elapsed since 1900.)
# (Month counts from 1 instead of 0. 10 is his October.)
my $dt = DateTime->new(
  year => 1964,
  month => 10,
  day => 16,
  hour => 16,
  minute => 12,
  second => 47,
);

# Get method to get time information
my $year = $dt->year;
my $mon = $dt->month;
my $mday = $dt->day;

# Day of the week number (day of the week starts with 1 and 1 is the month and 7 is the day)
my $wday = $dt->day_of_week;
my $hour = $dt->hour;
my $minute = $dt->minute;
my $second = $dt->second;
my $yday = $dt->day_of_year;
my $qtr = $dt->quarter;

print "(1) Date/time information of DateTime\n";
print(
  "${year} year ${mon} month ${mday} day ${wday} th day\n".
  "${hour} hours ${minute} minutes ${second} seconds\n".
  "${yday} day (counting in one year)\n".
  "${qtr} period (out of quarter)\n"
);

Output

(1) Date/time information of DateTime
October 16, 1964 5th day of the week
16:12:47
Day 290 (counting in one year)
4th term (out of 4th half)

This is an example to get the current date and time.

use strict;
use warnings;
use DateTime;

# (1) -1 Get the current time(local time)
my $dt = DateTime->now(time_zone =>'local');

# (1) -2 When explicitly specifying the time zone.
# my $dt = DateTime->now(time_zone =>'Asia/Tokyo');

# (1) -3 UTC Coordinated Universal Time
# my $dt = DateTime->now;

# Get method to get time information
my $year = $dt->year;
my $mon = $dt->month;
my $mday = $dt->day;
my $wday = $dt->day_of_week;
my $hour = $dt->hour;
my $minute = $dt->minute;
my $second = $dt->second;
my $yday = $dt->day_of_year;
my $qtr = $dt->quarter;

print "(1) Get the current time.\n";
print(
  "${year} year ${mon} month ${mday} day ${wday} th day\n".
  "${hour} hours ${minute} minutes ${second} seconds\n".
  "${yday} day (counting in one year)\n".
  "${qtr} period (out of quarter)\n"
);

Output

(1) Get the current time.
November 2, 2008 7th day of the week
8:11:05
Day 307 (counting in one year)
4th term (out of 4th half)

This is an example to create date information from epoch seconds.

use strict;
use warnings;
use DateTime;

# Create date information from epoch seconds.
my $epoch = 1225589752;
my $dt = DateTime->from_epoch(epoch => $epoch);

# Get method to get time information
my $year = $dt->year;
my $mon = $dt->month;
my $mday = $dt->day;
my $wday = $dt->day_of_week; # Day of the week number (day of the week starts with 1 and 1 is the month and 7 is the day)
my $hour = $dt->hour;
my $minute = $dt->minute;
my $second = $dt->second;
my $yday = $dt->day_of_year;
my $qtr = $dt->quarter;

print "(1) Create date information from epoch seconds.\n";
print(
  $year, "year",
  $mon, "month",
  $mday, "day",
  $wday, "third day\n",
  $hour, "hour",
  $minute, "minute",
  $second, "seconds\n",
  $yday, "Day (counting in one year)\n",
  $qtr, "Period (out of quarter)\n"
);

Output

(1) Create date information from epoch seconds.
November 2, 2008 7th day of the week
1:35:52
Day 307 (counting in one year)
4th term (out of 4th half)

This is an example to specify the time zone.

use strict;
use warnings;
use DateTime;
use DateTime::TimeZone;

# (1) Creating a timezone object
my $time_zone = DateTime::TimeZone->new(name =>'Asia/Tokyo');

# When automatically acquiring the time zone from the OS settings
# my $time_zone = DateTime::TimeZone->new(name =>'local');
                                                     
# (2) Use of timezone object
my $dt1 = DateTime->now(time_zone => $time_zone);
my $dt2 = DateTime->now(time_zone => $time_zone);

This is an example to set the locale.

use strict;
use warnings;
use DateTime;
use Encode;

print "(1) Print the month name and day of the week name in Japanese.\n";
my $dt = DateTime->now(locale =>'ja', time_zone =>'local');

# Month name
my $month_name = $dt->month_name;

# Month abbreviation (same as month name if there is no abbreviation)
my $month_abbr = $dt->month_abbr;

# Day of the week name
my $day_name = $dt->day_name;

# Abbreviated name of the day of the week
my $day_abbr = $dt->day_abbr;

# Since the UTF-8 flag is set, encode it.
my $encode_to;
if ($^O eq 'MSWin32') {$encode_to = 'shift-jis'}
else {$encode_to = 'utf8'}

print(
  encode($encode_to, $month_name) . "\n".
  encode($encode_to, $month_abbr) . "\n".
  encode($encode_to, $day_name) . "\n".
  encode($encode_to, $day_abbr) . "\n"
);

Output result

(1) Output the month name and day of the week in Japanese.
November
November
Friday
Money

This is an example to specify the locale with DateTime.

use strict;
use warnings;
use DateTime;
use DateTime::Locale;

# For encoding
use Encode;
my $encode_to;
if ($^O eq 'MSWin32') {$encode_to = 's
hift-jis'}
else {$encode_to = 'utf8'}

# Generation of locale
print "(1) DateTime::Locale object\n";
my $locale = DateTime::Locale->load('ja');
my $dt = DateTime->now(locale => $locale, time_zone =>'local');

# Day of the week name
my $day_name = $dt->day_name;
print encode($encode_to, $day_name) . "\n";

This is an example to get the date and time.

use strict;
use warnings;
use DateTime;
use DateTime::TimeZone;
use DateTime::Locale;

my $dt = DateTime->now(time_zone =>'local');

print "(1) Convenient output method of DateTime date/time\n";
my $ymd = $dt->ymd;
my $ymd_slash = $dt->ymd('/');
my $mdy = $dt->mdy;
my $mdy_slash = $dt->mdy('/');
my $dmy = $dt->dmy;
my $dmy_slash = $dt->dmy('/');
my $hms = $dt->hms;
my $hms_hyphen = $dt->hms('-');
my $ymdhms = $dt->datetime;

print(
  "Date (hyphen) $ymd\n".
  "Date (slash) $ymd_slash\n".
  "Month, day, year (hyphen) $mdy\n".
  "Month, day, year (slash) $mdy_slash\n".
  "Day/month/year (hyphen) $dmy\n".
  "Day/month/year (slash) $dmy_slash\n\n".
  "Hour, minute, second (colon) $hms\n".
  "Hour, minute and second (hyphen) $hms_hyphen\n\n".
  "Year/month/day/hour/minute/second $ymdhms\n"
);

This is an example to get the leap year judgment and the last day of the month.

use strict;
use warnings;
use DateTime;

print "(1) Determine if it is a leap year.\n";
my $dt1 = DateTime->now(time_zone =>'local');
my $is_leap_year = $dt1->is_leap_year;
if ($is_leap_year) {print "This year is a leap year.\n\n"}
else {print "This year is not a leap year.\n\n"}

print "(2) Get the last day of the month.\n";
my $dt2 = DateTime->last_day_of_month(year => 2008, month => 11);
print "The last day of November 2008 is". $Dt2->day. "The day.\n";

This is an example strftime method. I'm trying all the formats with examples.

use strict;
use warnings;
use DateTime;

print "(1) strftime format specification list\n";
my $dt = DateTime->now(time_zone =>'local');

print'%a: Abbreviation for day of the week:'. $Dt->strftime("%a") . "\n";
print'%A: Day of the week name:'. $Dt->strftime("%A") . "\n";
print'%b: month abbreviation:'. $dt->strftime("%b") . "\n";
print'%B: month name:'. $dt->strftime("%B") . "\n";
print'%c: default format:'. $Dt->strftime("%c") . "\n";
print'%C: First two digits of the year:'. $Dt->strftime("%C") . "\n";
print'%d: days (01 to 31):'. $Dt->strftime("%d") . "\n";
print'%D: Same as%m /%d /%y. Month Day Year:'. $Dt->strftime("%D") . "\n";
print'%e: day (1 to 31) The second digit of the one digit number (1 to 9) is a space. :'
  . $dt->strftime("%e") . "\n";
print'%F: Same as%Y-%m-%d (eg 2008-11-31):'. $Dt->strftime("%F") . "\n";
print'%G: Year (I don't know the difference from%Y):'. $Dt->strftime("%G") . "\n";
print'%g: Last two digits of the year (00-99):'. $Dt->strftime("%g") . "\n";
print'%h: Same as%b. Month abbreviation:'. $Dt->strftime("%h") . "\n";
print'%H: Hour (00 to 23):'. $Dt->strftime("%H") . "\n";
print'%I: Hour (01 to 12) Time in 12-hour notation:'. $Dt->strftime("%I") . "\n";
print'%j: What day is it for the first time in the year? (001 to 366):'
  . $dt->strftime("%j") . "\n";
print'%k: Hour (0 to 23) The second digit of the one digit number (0 to 9) is a space. :'
  . $dt->strftime("%k") . "\n";
print'%l: Hour (1 to 12) Time in 12-hour notation:'. $Dt->strftime("%l") . "\n";
print'%m: Month number (01 to 12):'. $Dt->strftime("%m") . "\n";
print'%M: Minutes (00 to 59):'. $Dt->strftime("%M") . "\n";
print'%n: Newline character:'. $Dt->strftime("%n") . "\n";
print'%N: milliseconds (write%3N will display milliseconds in 3 digits and%6N will display milliseconds in 6 digits):'
  . $dt->strftime("%3N") . "\n";
print'%p: AM or PM:'. $Dt->strftime("%p") . "\n";
print'%P: am or pm:'. $Dt->strftime("%P") . "\n";
print'%r:%I:%M:%S Same as%p. (11:55:23 PM, etc.):'
  . $dt->strftime("%r") . "\n";
print'%R: hours and minutes (15:16, etc.):'. $Dt->strftime("%R") . "\n";
print'%s: seconds from epoch:'. $dt->strftime("%s") . "\n";
print'%S: seconds (00 to 61):'. $Dt->strftime("%S") . "\n";
print'%t: tab character:'. $Dt->strftime("%t") . "\n";
print'%T: Same as%H:%M:%S. Hours, minutes and seconds (such as 23:14:03):'
  . $dt->strftime("%T") . "\n";
print'%u: Day of the week number (1 to 7. Monday is 1):'. $Dt->strftime("%u") . "\n";
print'%U: How many weeks from the beginning of the year? First Sunday of the year (00-53)'
  Count'.'As the beginning of the week. The first Sunday week is 01. The week before that was 00. :'
  . $dt->strftime("%U") . "\n";
print'%V: How many weeks from the beginning of the year? (01-53) Weeks with at least 4 days'
  .'Shall be the first week of the year. Count Monday as the beginning of the week. :'
  . $dt->strftime("%V") . "\n";
print'%w: Day of the week number (0 to 6. Sunday is 0):'. $Dt->strftime("%w") . "\n";
print'%W: Weeks counting from the beginning of the year (00-53) The first Monday of the year is the week'
  .'Count as the first. The first Monday week is 01. The week before that was 00. :'
  . $dt->strftime("%W") . "\n";
print'%x: default date format:'. $Dt->strftime("%x") . "\n";
print'%X: Default format for time:'. $Dt->strftime("%X") . "\n";
print'%y: last two digits of the year:'. $Dt->strftime("%y") . "\n";
print'%Y: Year:'. $Dt->strftime("%Y") . "\n";
print'%z: Time zone time shift from UTC (Coordinated Universal Time):'
  . $dt->strftime("%z") . "\n";
print'%Z: timezone name:'. $Dt->strftime("%Z") . "\n";
print'%%:%:'. $Dt->strftime("%%") . "\n";
print'%{method}:You can use the method of DateTime.pm. Example%{ymd}:'
  . $dt->strftime("%{ymd}") . "\n";

Output

(1) strftime format specification list
%a: Abbreviation for day of the week: Mon
%A: Day of the week name: Monday
%b: Month abbreviation: Nov
%B: Month name: November
%c: Default format: Nov 17, 2008 12:09:37 AM
%C: First two digits of the year: 20
%d: days (01 to 31): 17
%D: Same as%m /%d /%y. Date Year: 11/17/08
%e: Day (1 to 31) The second digit of the one digit number (1 to 9) is a space. : 17
%F: Same as%Y-%m-%d (for example, 2008-11-31): 2008-11-17
%G: Year (I don't know the difference from%Y): 2008
%g: Last 2 digits of year (00-99): 08
%h: Same as%b. Month abbreviation: Nov
%H: Hour (00 to 23): 00
%I: Hour (01 to 12) Time in 12-hour notation: 12
%j: What day is it for the first time from the beginning of the year? (001 to 366): 322
%k: Hour (0 to 23) The second digit of the one-digit number (0 to 9) is a space
NS. : 0
%l: Hour (1 to 12) Time in 12-hour notation The second digit of the one-digit number (0 to 9) is a space. : 12
%m: Month number (01 to 12): 11
%M: Minutes (00 to 59): 09
%n: Newline character:

%N: Milliseconds (Write%3N displays milliseconds in 3 digits,%6N displays milliseconds in 6 digits): 000
%p: AM or PM: AM
%P: am or pm: am
Same as%r:%I:%M:%S%p. (11:55:23 PM etc.): 12:09:37 AM
%R: Hours and minutes (15:16, etc.): 00:09
%s: Seconds from Epoch: 1226848177
%S: Seconds (00 to 61): 37
%t: tab character:
Same as%T:%H:%M:%S. Hours, minutes and seconds (such as 23:14:03): 00:09:37
%u: Day of the week number (1 to 7. Monday is 1): 1
%U: How many weeks from the beginning of the year? (00-53): Count the first Sunday of the year as the beginning of the week. The first Sunday week is 01. Before that
The week is 00. : 46
%V: How many weeks from the beginning of the year? (01-53): Let the week with at least 4 days be the first week of the year. Count Monday as the beginning of the week
NS. : 47
%w: Day of the week number (0 to 6. Sunday is 0): 1
%W: Weeks counting from the beginning of the year (00 to 53) Count the first Monday of the year as the beginning of the week. The first Monday week is 01. The week before that
Is 00. : 46
%x: Default date format: Nov 17, 2008
%X: Default format for time: 12:09:37 AM
%y: Last 2 digits of year: 08
%Y: Year: 2008
%z: Time zone time shift from UTC (Coordinated Universal Time): +0900
%Z: Timezone name: JST
%%:%:%
%{method}: DateTime.pm method can be used. %{ymd}: 2008-11-17

This is an example that calculates the date and time using DateTime.

use strict;
use warnings;
use DateTime;

print "(1) -1 Addition of dates\n";
my $dt = DateTime->now(time_zone =>'local');

# Addition of days
my $dt_tommorow = $dt->clone;
$dt_tommorow->add(days => 1);

# Monthly addition
my $dt_next_month = $dt->clone;
$dt_next_month->add(months => 1);

# Year addition
my $dt_next_year = $dt->clone;
$dt_next_year->add(years => 1);

print'Currently'. $Dt->date. ".\n\n";
print'Tomorrow'. $Dt_tommorow->date. ".\n";
print '1 year later'. $Dt_next_month->date. ".\n";
print '1 year later'. $Dt_next_year->date. ".\n\n";

# Hour addition
print "(1) -2 Add time\n";
my $dt_next_hour = $dt->clone;
$dt_next_hour->add(hours => 1);

# Addition of minutes
my $dt_next_minutes = $dt->clone;
$dt_next_minutes->add(minutes => 1);

# Addition of seconds
my $dt_next_second = $dt->clone;
$dt_next_second->add(seconds => 1);

print'Currently'. $Dt->time. ".\n\n";
print '1 hour later'. $Dt_next_hour->time. ".\n";
print '1 minute later'. $Dt_next_minutes->time. ".\n";
print '1 second later'. $Dt_next_second->time. ".\n";

Output

(1) -1 Date addition
Currently it is 2008-11-18.

Tomorrow is 2008-11-19.
One year later it will be 2008-12-18.
One year later it will be 2009-11-18.

(1) -2 Time addition
Currently it is 23:04:06.

One hour later it is 00:04:06.
One minute later it is 23:05:06.
One second later it is 23:04:07.

A sump that subtracts dates using DateTime.

use strict;
use warnings;
use DateTime;

print "(1) Date subtraction\n";
my $dt = DateTime->now(time_zone =>'local');

# Subtraction of days
my $dt_yesterday = $dt->clone;
$dt_yesterday->subtract(days => 1);

print'The current date is'. $Dt->date. ".\n";
print'Yesterday's date is'. $Dt_yesterday->date. ".\n\n";

# Combine addition and subtraction.
my $dt_mix = $dt->clone;
$dt_mix = $dt_mix->add(months => 1)->subtract(days => 1);

print "(2) Subtraction between DateTime objects\n";
my $dt1 = DateTime->new(year => 2000, month => 2, day => 1);
my $dt2 = DateTime->new(year => 2003, month => 3, day => 19);

my $duration = $dt2- $dt1;

print'Period'. $Duration->years.' Years and'
  . $duration->months.'Months and'
  . $duration->days. "Days\n";

Output

(1) Date subtraction
The current date is 2008-11-18.
Yesterday's date is 2008-11-17.

(2) Subtraction between DateTime objects
The period is 3 years, 1 month and 4 days

This is an example to get the period information.

use strict;
use warnings;
use DateTime;

# DateTime Subtraction between objects
my $dt1 = DateTime->new(
  year => 2000,
  month => 2,
  day => 1,
  hour => 12,
  minute => 44,
  second => 30
);

my $dt2 = DateTime->new(
  year => 2003,
  month => 3,
  day => 19,
  hour => 23,
  minute => 54,
  second => 40
);

my $duration = $dt2- $dt1;

print "(1) Get the period.\n";
print "Period is". $Duration->years. "Year and"
  . $duration->months. "Months and"
  . $duration->days. "Days and"
  . $duration->hours. "Time and"
  . $duration->minutes. "minutes and"
  . $duration->seconds. "Seconds\n\n";

print "(2) Determine the order of the periods.\n";
if ($duration->is_positive) {
  print "\$dt2 is a date after \$dt1.\n";
}
elsif ($duration->is_zero) {
  print "\$dt2 is equal to \$dt1.\n";
}
elsif ($duration->is_negative) {
  print "\$dt2 is a date before \$dt1.\n";
}
print "\n";

print "(3) Get the period on a monthly basis.\n";
print'The period is'. $Duration->in_units('months'). "Months.\n";

Output

(1) Get the period.
The period is 3 years, 1 month, 4 days, 11 hours, 10 minutes and 10 seconds.

(2) Determine the sign of the period.
$dt2 is a date after $dt1.

(3) Obtain the period on a monthly basis.
The period is 37 months on a monthly basis.

Related Informatrion