[Code Sea Pick-up Bay Perl] get date and date plus minus

Source: Internet
Author: User


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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.