perl Date - ghdrako/doc_snipets GitHub Wiki

Time::Piece

use Time::Piece;  
print localtime->strftime("%Y/%m/%d %H:%M:%S"); 

Time::Piece has been in perl core since 5.8

POSIX

use strict;
use warnings;

use POSIX qw/strftime/;
# POSIX function strftime() to format date and time
# doc https://metacpan.org/pod/POSIX


# localtime() function, which returns values for the current date and time if given no arguments. Following is the 9-element list returned by the localtime function while using in list context −
# sec,     # seconds of minutes from 0 to 61
# min,     # minutes of hour from 0 to 59
# hour,    # hours of day from 0 to 24
# mday,    # day of month from 1 to 31
# mon,     # month of year from 0 to 11
# year,    # year since 1900
# wday,    # days since sunday
# yday,    # days since January 1st
# isdst    # hours of daylight savings time





sub is_dec_proc {
 my @t = localtime;
 my $flag;
 return $t[3] >= 11?1:0;
}
 

my $curr_date = strftime('%Y%m%d',localtime);

print "current date:",$curr_date,"\n";;

#------------------------------------------------
# two month ago
my @t = localtime;
$t[4] -= 2;  # $t[4] is tm_mon
my $two_months_ago = strftime('%Y%m%d',@t);
print "two month ago:",$two_months_ago,"\n";

#------------------------------------------------
# last_day_prev_month
my @t1 = localtime;
$t1[3] = 0;
my $last_day_prev_month = strftime('%Y%m%d',@t1);
print "last_day_prev_month:",$last_day_prev_month,"\n";

print substr($last_day_prev_month,-2),"\n";


print is_dec_proc();
print "\n";


print strftime '%Y-%m-%d', gmtime();  # print cuurent Greenwich time w formacie yyyy-mm-dd
print "\n";
print strftime '%Y-%m-%d-%H-%M-%S', gmtime(); # w formacie yyyy-mm-dd--hh24-mi-ss
print "\n";
my $datestring = strftime "%a %b %e %H:%M:%S %Y", localtime;
print $datestring,"\n";

# %%      PERCENT
# %a      day of the week abbr
# %A      day of the week
# %b      month abbr
# %B      month
# %c      MM/DD/YY HH:MM:SS
# %C      ctime format: Sat Nov 19 21:05:57 1994
# %d      numeric day of the month, with leading zeros (eg 01..31)
# %e      like %d, but a leading zero is replaced by a space (eg  1..32)
# %D      MM/DD/YY
# %G      GPS week number (weeks since January 6, 1980)
# %h      month abbr
# %H      hour, 24 hour clock, leading 0's)
# %I      hour, 12 hour clock, leading 0's)
# %j      day of the year
# %k      hour
# %l      hour, 12 hour clock
# %L      month number, starting with 1
# %m      month number, starting with 01
# %M      minute, leading 0's
# %n      NEWLINE
# %o      ornate day of month -- "1st", "2nd", "25th", etc.
# %p      AM or PM 
# %P      am or pm (Yes %p and %P are backwards :)
# %q      Quarter number, starting with 1
# %r      time format: 09:05:57 PM
# %R      time format: 21:05
# %s      seconds since the Epoch, UCT
# %S      seconds, leading 0's
# %t      TAB
# %T      time format: 21:05:57
# %U      week number, Sunday as first day of week
# %w      day of the week, numerically, Sunday == 0
# %W      week number, Monday as first day of week
# %x      date format: 11/19/94
# %X      time format: 21:05:57
# %y      year (2 digits)
# %Y      year (4 digits)
# %Z      timezone in ascii. eg: PST
# %z      timezone in format -/+0000








# %Y    Year        YYYY                                                 2014
# %m    Month       mm                                                     11
# %d    Day         dd                                                     09
# %H    Hour        HH                                                     08
# %M    Min         MM                                                     05
# %S    Seconds     SS  
# %j   Day of the year as a zero-padded decimal number. 0n January 1 this will be 001
# %w   Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.
# %U   Week number of the year as a zero padded decimal number.(Sunday as the first day of the week)
#      All days in a new year preceding the first Sunday
#      are considered to be in week 0

# %W   Week number of the year as a decimal number.(Monday as the first day of the week)
#      All days in a new year preceding the first Monday
#      are considered to be in week 0.



sub gen_last_day_prev_mth {
        my @t = localtime;
        $t[3] = 0; #day
		#$t[4] -= 1;
    return strftime('%Y%m%d',@t);
};
my $yyyymmdd = gen_last_day_prev_mth();
print "last day prev month:",$yyyymmdd;

Benchmark

use Benchmark;
$t0 = Benchmark->new;
# ... your code here ...
$t1 = Benchmark->new;
$td = timediff($t1, $t0);
print "the code took:",timestr($td),"\n";

use Benchmark qw( cmpthese ) ;
$x = 3;
cmpthese( -5, {
    a => sub{$x*$x},
    b => sub{$x**2},
} );



use Benchmark qw( timethese cmpthese ) ;
$x = 3;
$r = timethese( -5, {
    a => sub{$x*$x},
    b => sub{$x**2},
} );
cmpthese $r;


$result = timethis(100000, sub { ... });
print "total CPU = ", $result->cpu_a, "\n";

HiRes

#High resolution alarm, sleep, gettimeofday, interval timers

use Time::HiRes qw( usleep ualarm gettimeofday tv_interval nanosleep clock_gettime clock_getres clock_nanosleep clock stat lstat utime);

# signal alarm in 2.5s & every .1s thereafter
ualarm(2_500_000, 100_000);
# cancel that ualarm
ualarm(0);


# measure elapsed time 
# (could also do by subtracting 2 gettimeofday return values)
$t0 = [gettimeofday];
# do bunch of stuff here
$t1 = [gettimeofday];
# do more stuff here
$t0_t1 = tv_interval $t0, $t1;

$elapsed = tv_interval ($t0, [gettimeofday]);
$elapsed = tv_interval ($t0);	# equivalent code



use Time::HiRes qw(gettimeofday tv_interval);
$t0 = [gettimeofday];
$elapsed = tv_interval($t0)

or    
use Time::HiRes qw(time);
$t0 = time;
$elapsed = time - $t0;

DataTime

use strict;
use warnings;

use POSIX qw/strftime/;
use v5.10;
use DateTime;
use DateTime::Duration;

sub gen_last_day_prev_mth {
        my @t = localtime;
        $t[3] = 0; #day
		#$t[4] -= 1;
    return strftime('%Y%m%d',@t);
}

#print localtime,"\n";
my $yyyymmdd = gen_last_day_prev_mth();
print "last day prev month:",$yyyymmdd,"\n";


my $datestring = strftime "%Y %m %d %H:%M:%S %Y", localtime;
print "current date:",$datestring,"\n";

say "----------------------------------------";

my $dt = DateTime->now;

# DateTime->now( ... )
# DateTime->today( ... )  equivalent to DateTime->now(@_)->truncate( to => 'day' );
# DateTime->last_day_of_month( ... )
# DateTime->from_day_of_year( ... )
# $dt->year()
# $dt->month()
# $dt->month_name()
# $dt->day()
# $dt->day_of_week() 1 being Monday and 7 being Sunday
# $dt->local_day_of_week()  The day corresponding to 1 will vary based on the locale
# $dt->day_name()
# $dt->day_of_year()
# $dt->quarter()
# $dt->quarter_name()
# $dt->day_of_quarter()
# $dt->weekday_of_month()

# $dt->is_leap_year()
# $dt->is_last_day_of_month()
# $dt->is_last_day_of_quarter()
# $dt->is_last_day_of_year()
# $dt->month_length()

# $dt->set( .. )
# $dt->set_year()
# $dt->set_month()
# $dt->set_day()
# $dt->set_hour()
# $dt->set_minute()
# $dt->set_second()

# $dt->truncate( to => ... ) reset some of the local time components in the object to their "zero" values
# $dt->truncate( to => month ) local day becomes 1, and the hour, minute, and second all become 0.
# $dt->truncate( to => week ) datetime is set to the Monday of the week in which it occurs, and the time components are all set to 0

# date math
# $dt->add( days => 1 )->subtract( seconds => 1 );

# my $dt = DateTime->new( year => 2003, month => 2, day => 28 );
# $dt->add( months => 1, days => 1 );
# $dt->add( months => 1 )->add( days => 1 );

say "current:",$dt;
 
my $day_before = $dt - DateTime::Duration->new( days => 1 );
say "day_before:",$day_before;
 
my $day_after = $dt + DateTime::Duration->new( days => 1 );
say "day_after:",$day_after;
 
my $year_before = $dt - DateTime::Duration->new( years => 1 );
say "year_before:",$year_before;

my $month_before = $dt - DateTime::Duration->new( months => 1 );
say "month_before:",$month_before;
my $last_day_of_prev_month = DateTime->last_day_of_month(
    year  => $month_before->year,
    month => $month_before->month,
);
say "last_day_of_prev_month:",$last_day_of_prev_month;

say "aln_day:",$last_day_of_prev_month->strftime("%d");
say "yyyymm:",$last_day_of_prev_month->strftime("%Y%m");
say "yymm:",$last_day_of_prev_month->strftime("%y%m");
say "year_nbr:",$last_day_of_prev_month->strftime("%Y");
say "mth_nbr:",$last_day_of_prev_month->strftime("%m");
say "end_day:",$last_day_of_prev_month->day();
say "yer_nbr_old :",$last_day_of_prev_month->subtract( years => 1 )->strftime("%Y");
say "yyyymm12_old :",$last_day_of_prev_month->subtract( years => 1 )->strftime("%Y"),'12';
say "XXX";


die $dt->datetime();


# $t[4] -= 1;

DateFormat

#This module provides routines to format dates into ASCII strings. They correspond to the C library routines strftime and ctime.



use Date::Format;
 
@lt = localtime(time);
 
print time2str($template, time);
print strftime($template, @lt);
 
print time2str($template, time, $zone);
print strftime($template, @lt, $zone);
 
print ctime(time);
print asctime(@lt);
 
print ctime(time, $zone);
print asctime(@lt, $zone);


my $lang = Date::Language->new('German');
$lang->time2str("%a %b %e %T %Y\n", time);




# %%      PERCENT
# %a      day of the week abbr
# %A      day of the week
# %b      month abbr
# %B      month
# %c      MM/DD/YY HH:MM:SS
# %C      ctime format: Sat Nov 19 21:05:57 1994
# %d      numeric day of the month, with leading zeros (eg 01..31)
# %e      like %d, but a leading zero is replaced by a space (eg  1..32)
# %D      MM/DD/YY
# %G      GPS week number (weeks since January 6, 1980)
# %h      month abbr
# %H      hour, 24 hour clock, leading 0's)
# %I      hour, 12 hour clock, leading 0's)
# %j      day of the year
# %k      hour
# %l      hour, 12 hour clock
# %L      month number, starting with 1
# %m      month number, starting with 01
# %M      minute, leading 0's
# %n      NEWLINE
# %o      ornate day of month -- "1st", "2nd", "25th", etc.
# %p      AM or PM 
# %P      am or pm (Yes %p and %P are backwards :)
# %q      Quarter number, starting with 1
# %r      time format: 09:05:57 PM
# %R      time format: 21:05
# %s      seconds since the Epoch, UCT
# %S      seconds, leading 0's
# %t      TAB
# %T      time format: 21:05:57
# %U      week number, Sunday as first day of week
# %w      day of the week, numerically, Sunday == 0
# %W      week number, Monday as first day of week
# %x      date format: 11/19/94
# %X      time format: 21:05:57
# %y      year (2 digits)
# %Y      year (4 digits)
# %Z      timezone in ascii. eg: PST
# %z      timezone in format -/+0000

DateSimple

use Date::Simple qw/today ymd date d8/;
use 5.010;

my $d = today;
$d = ymd($d->year, $d->month, 1) - 1;
say "last day previous month: ",$d;


# Difference in days between two dates:
$diff = date('2001-08-27') - date('1977-10-05');
say "Differ ",$diff," days";

# Offset $n days from now:
$date = today() + $n;
say $date;  # uses ISO 8601 format (YYYY-MM-DD)


my $date  = Date::Simple->new('1972-01-17');
my $year  = $date->year;
my $month = $date->month;
my $day   = $date->day; 
# or my ($year, $month, $day) = $date->as_ymd;


my $date2 = ymd($year, $month, $day);
my $date3 = d8('19871218');
my $today = today();
my $tomorrow = $today + 1;  #my $tomorrow = $today->next;  my $yesterday = $today->prev;

if ($tomorrow->year != $today->year) {
    print "Today is New Year's Eve!\n";
}
 
if ($today > $tomorrow) {
    die "warp in space-time continuum";
}
 
print "Today is ";
print(('Sun','Mon','Tues','Wednes','Thurs','Fri','Satur')[$today->day_of_week]);
print "day.\n";


if ($date cmp "2001-07-01") {
 say "sss";
}

if ($date <=> [2001, 7, 1]) {
 say "aaa";
}


#DATE->as_str ([STRING])
#DATE->format ([STRING])
#DATE->strftime ([STRING])

my $iso_date1 = $date->format("%Y-%m-%d");


#UTILITIES
#leap_year (YEAR)  - Returns true if YEAR is a leap year.
#days_in_month (YEAR, MONTH)  - Returns the number of days in MONTH, YEAR.
#leap_year (YEAR) - Returns true if YEAR is a leap year.
#days_in_month (YEAR, MONTH) - Returns the number of days in MONTH, YEAR.

#OPERATORS
#DATE + NUMBER
#DATE - NUMBER  You can construct a new date offset by a number of days using the + and - operators.
#DATE += NUMBER
#DATE -= NUMBER
#DATE1 - DATE2
#You can subtract two dates to find the number of days between them.
#DATE1 == DATE2
#DATE1 < DATE2
#DATE1 <=> DATE2
#DATE1 cmp DATE2

DateLocale