Comprehensive summary of php date and time operations _ php tips-php Tutorial

Source: Internet
Author: User
This article focuses on php date and time operations, involving a comprehensive range of knowledge points. if you are interested, you can refer to the example to introduce several core functions:
Mktime function
The mktime () function returns the Unix timestamp of a date.
The parameter always represents the GMT date, so is_dst has no effect on the result.
The parameters can be left empty from right to left. the blank parameters are set to the corresponding current GMT value.
Syntax: Mktime (hour, minute, second, month, day, year, is_dst)
Parameter description
Hour is optional. The specified hour.
Minute is optional. Minutes.
Second is optional. Specified seconds.
Month is optional. Indicates the month in number.
Day is optional. Specified day.
Year is optional. Specified year. In some systems, the valid value ranges from 1901 to 2038. However, this restriction does not exist in PHP 5.
Is_dst is optional. If the time is in the daylight saving time (DST) period, it is set to 1; otherwise, it is set to 0. if it is unknown, it is set to-1.
The is_dst parameter has been deprecated since 5.1.0. Therefore, the new time zone processing feature should be used.
Example: the mktime () function is very useful for date calculation and verification. It can automatically correct out-of-range input:

<?php echo(date("M-d-Y",mktime(0,0,0,12,36,2001))); echo(date("M-d-Y",mktime(0,0,0,14,1,2001))); echo(date("M-d-Y",mktime(0,0,0,1,1,2001))); echo(date("M-d-Y",mktime(0,0,0,1,1,99))); ?> 

Output:

Jan-05-2002 Feb-01-2002 Jan-01-2001 Jan-01-1999 

Strtotime function
The strtotime () function parses the date and time descriptions of any English text into Unix timestamps.
Syntax:Strtotime (time, now)
Parameter description
Time specifies the time string to be parsed.
Now is used to calculate the timestamp of the returned value. If this parameter is omitted, the current time is used.
One week later: strtotime ("+ 1 week ");
One week ago: strtotime ("-1 week ");
After December January: strtotime ("+ 1 months ");
One day later: strtotime ("+ 1 days ");
30 seconds later strtotime ("+ 30 seconds ");
After 20 minutes, strtotime ("+ 20 minutes ");
Strtotime ("+ 12 hours") after 12 hours ");

Date function
The date () function is used to format a local time/date.
Syntax
Date (format, timestamp)
Date_default_timezone_set function
The date_default_timezone_set () function is used to set the default time zone of all date/time functions in the script.
Date_default_timezone_set (timezone)

Instance

First caseIf there is no database, and the obtained date value is compared, you have to use the php time and date function for computation, as shown below:

For example, to calculate the number of days from:

<? Php $ startdate = strtotime ("2015-9-5"); $ enddate = strtotime ("2015-9-18"); // The above php time and date function has changed the date to the timestamp, is converted to seconds. In this way, we only need to subtract the two values and then convert the second to the day. the comparison is simple, as shown below: $ days = round ($ enddate-$ startdate)/3600/24 ); echo $ days; // days indicates the number of days.?>

SecondChild Growth

<? Date_default_timezone_set ('Asia/Shanghai'); // the preceding statement sets the time zone. In fact, it is fine if no time zone is set. However, when zde is debug, a prompt will be displayed, indicating what unsafe functions to say... Add it. Echo date ('Y-m-d H: I: s '). 'Today is '. date ('Y '). 'year '. date ('w '). 'Week'; $ stime = '2017-11-03 '; echo"

*** Since birth ($ stime... :

"; Echo" today is the first". Lnbsp (daysofnow ($ stime), 3 )."Days
"; Echo" today is the first". Lnbsp (weeksofnow ($ stime), 3 )."Week
"; Echo" today is the first". Lnbsp (monthsofnow ($ stime), 3 )."Months
"; Echo" today is the first". Lnbsp (yearsofnow ($ stime), 3 )."Year
";/* $ Output = sprintf (" Today is the first% 03dDays
Today is the day <font color = red>% 03dWeek
Today is the day <font color = red>% 03dMonths
Today is the day <font color = red>% 03dYear
....
". Date ('W', $ ntemp )."
"; Return ($ ntemp-$ ftemp)/60/60/24/7;} function daysofnow ($ stime) {$ ftime = strtotime ($ stime ); return ceil (abs (time ()-$ ftime)/(60*60*24);} function monthsofnow ($ stime) {$ ftime = strtotime ($ stime); $ fmonth = date ('M', $ ftime); $ fyear = date ('Y', $ ftime ); $ nmonth = date ('M'); $ nyear = date ('Y'); $ result = ($ nyear-$ fyear) * 12 + $ nmonth-$ fmonth + 1; return $ result;} function yearsofnow ($ stime) {$ ftime = strtotime ($ s Time); $ fyear = date ('Y', $ ftime); $ nyear = date ('Y'); return $ nyear-$ fyear + 1 ;} // the following functions are only used with spaces. they are not the core content. they are only beautiful functions Lnbsp ($ data, $ num) {$ result = trim ($ data ); for ($ I = $ num; $ I >= strlen ($ data); $ I --) {$ result = ''. $ result;} return $ result;}?>

Case 3:You can use the following code tomorrow, next month, and next year:

$tomorrow = date('Y-m-d',mktime (0,0,0,date("m"),date("d")+1,date("Y"))); $nextmonth = date('Y-m',mktime (0,0,0,date("m")+1,date("d")+1,date("Y"))); $nextyear = date('Y',mktime (0,0,0,date("m"),date("d"),date("Y")+1));  echo $tomorrow.'
'; echo $nextmonth.'
'; echo $nextyear.'
';

Case 4:Working hours (excluding holidays)

<? $ StartDate = "2001-12-12"; $ endDate = "2002-11-1"; $ holidayArr = array ("05-01", "05-02", "10-01 ", "10-01", "10-02", "10-03", "10-04", "10-05", "01-26 ", "01-27", "01-28", "01-29"); // holiday date array, such as $ endWeek = 2 for the National Day, May Day, and Spring Festival; // whether you have a weekend break. the double break is 2, the Sunday break is 1, and the zero rest is 0 $ beginUX = strtotime ($ startDate); $ endUX = strtotime ($ endDate); for ($ n = $ beginUX; $ n <= $ endUX; $ n = $ n + 86400) {$ week = date ("w", $ n); $ MonDay = date ("m-d ", $ n); if ($ endWeek) {// weekend break away if ($ endWeek = 2) {if ($ week = 0 | $ week = 6) continue;} if ($ endWeek = 1) {if ($ week = 0) continue;} if (in_array ($ MonDay, $ holidayArr) continue; $ totalHour + = 10; // work 10 hours a day} echo "start date: $ startDate
"; Echo" end date: $ endDate
"; Echo" spent a total of ". $ totalHour." hours ";?>


Fifth case:Returns the hour in seconds.

<?php function transform($sec){   $output = '';   $hours = floor($sec / 3600);  $remainSeconds = $sec % 3600;   $minutes = floor($remainSeconds / 60);  $seconds = $sec - $hours * 3600 - $minutes * 60;   if($sec >= 3600){  $output .= $hours.' h / ';  $output .= $minutes.' m / ';  }   if($sec >= 60 && $sec < 3600){  $output .= $minutes.' m / ';  }   return $output .= $seconds.' s '; }  echo transform(3231803);  ?> 

The above are all examples of php date and time operations provided for everyone. I hope this will be helpful for everyone's learning.

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.