In PHP, if we want to add or subtract time and date, we can use two functions, mktime and strtotime functions. Let me introduce to you how to use them.
mktime function
The mktime() function returns the Unix timestamp of a date.
The argument always represents a GMT date, so is_dst has no effect on the result.
The parameters can be left empty in order from right to left, and the empty parameters will be set to the corresponding current GMT value.
Parameter Description
hour optional. Specified hours.
minute is optional. Specified minutes.
second is optional. Specifies seconds.
month is optional. Specifies the numeric month.
day is optional. Specify days.
year is optional. Specified year. On some systems, legal values are between 1901 - 2038. However, this limitation no longer exists in PHP 5.
is_dst Optional. Set to 1 if the time is during Daylight Saving Time (DST), 0 otherwise, or -1 if unknown.
Example
The mktime() function is very useful for date operations and verification. It can automatically correct out-of-bounds input:
The code is as follows | Copy code | ||||||||||||
echo(date("M-d-Y",mktime(0,0,0,14,1,2001)));
Output:
Feb-01-2002 Jan-01-2001 Jan-01-1999 |
The code is as follows | Copy code |
function getTheMonday($date) { if (date ( 'N', strtotime ( $date ) ) == 1) { Return date ( 'Y-m-d', strtotime ( 'Monday', strtotime ( $date ) ) ); } else { Return date ( 'Y-m-d', strtotime ( 'last Monday', strtotime ( $date ) ) ); } } |
The code is as follows | Copy code |
function getTheSunday($date) { return date ( 'Y-m-d', strtotime ( 'Sunday', strtotime ( $date ) ) ); } |