Preface
In Perl, you can use localtime to get local dates and times without installing other modules.
In a scalar context, the string format is returned.
my $ localtime = localtime ();
print "\ n $ localtime \ n";
return:
Thu Jan 1 18:17:56 2015
In the context of a list, a list of elements describing the current time is returned
my ($ sec, $ min, $ hour, $ mday, $ mon, $ year_off, $ wday, $ yday, $ isdat) = localtime ();
$ sec seconds, 0 ~ 59
$ min points, 0 ~ 59
$ hour, 0 ~ 23
$ mday The day of the month, 1 ~ 2 8, 2, 9, 30, or 3 1
$ mon Month in year, 0 ~ 11 (please be careful here)
$ year_off Year since 1900. Add this number to 1900 to get the correct 4-digit year
$ wday day of the week, 0 ~ 6
$ yday Day of the year, 0 ~ 364 or 365
$ isdst is true if daylight saving time is in effect
So the date obtained this way:
The year needs to add 1900: $ year + = 1900;
The month needs to be increased by one: $ mon + = 1;
Several methods
Get the current date:
sub get_current_day
{
my ($ sec, $ min, $ hour, $ day, $ mon, $ year) = localtime ();
$ mon ++; $ year + = 1900;
my $ data_now = sprintf ("% 04d /% 02d /% 02d", $ year, $ mon, $ day);
return $ data_now;
}
If you want to get the date of the previous day, you cannot simply subtract one from the above date. If so, you will have problems when you cross the month:
The correct one is time minus 86400 seconds (24 hours)
sub get_last_day
{
my ($ sec, $ min, $ hour, $ day, $ mon, $ year) = localtime (time ()-86400);
$ mon ++; $ year + = 1900;
my $ data_now = sprintf ("% 04d /% 02d /% 02d", $ year, $ mon, $ day);
return $ data_now;
}
Get the date of the last few days:
sub get_last_number_day
{
my ($ lastNumber) = @_;
my ($ sec, $ min, $ hour, $ day, $ mon, $ year) = localtime (time ()-86400 * $ lastNumber);
$ mon ++; $ year + = 1900;
my $ data_now = sprintf ("% 04d /% 02d /% 02d", $ year, $ mon, $ day);
return $ data_now;
}
[Codel Perl] Get Date and Date Addition