Perl Language

Dates and Time

Create new DateTime

Install DateTime on your PC and then use it in perl script:

use DateTime;

Create new current datetime

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

Then you can access elements’s values of date and time:

$year   = $dt->year;
$month  = $dt->month;
$day    = $dt->day;
$hour   = $dt->hour;
$minute = $dt->minute;
$second = $dt->second;

To get only time:

my $time = $dt->hms; #return time with format hh:mm:ss

To get only date:

my $date = $dt->ymd; #return date with format yyyy-mm-dd

Working with elements of datetime

Set single element:

$dt->set( year => 2016 );

Set many elements:

$dt->set( year => 2016, 'month' => 8);

Add duration to datetime

$dt->add( hour => 1, month => 2)

Datetime subtraction:

my $dt1 = DateTime->new(
      year      => 2016,
      month     => 8,
      day       => 20,
);

my $dt2 = DateTime->new(
      year      => 2016,
      month     => 8,
      day       => 24,
);

my $duration = $dt2->subtract_datetime($dt1);
print $duration->days

You will get the result is 4 days

Calculate code execution time

use Time::HiRes qw( time );

my $start = time();

#Code for which execution time is calculated
sleep(1.2);

my $end = time();

printf("Execution Time: %0.02f s\n", $end - $start);

This will print execution time of Code in seconds


This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow