Home > Article > Backend Development > php date and time_PHP tutorial
PHP provides a large number of built-in functions, which allows developers to manage time with ease and greatly improves work efficiency. Today we will introduce some common PHP date and time functions and date and time processing to students.
9.1 Commonly used date and time processing functions
Table 9-1: Commonly used date and time processing functions
Function
Say Ming
checkdate
Verify the time function to determine whether the time is valid, return true if valid, otherwise return false
date_default_timezone_get
Get the default time zone used by script datetime functions
date_default_timezone_set
Set the default time zone for date and time functions
date
Format a local time/date
getdate
Get date/time information
gettimeofday
Get current time
localtime
Get local time
microtime
Returns the current timestamp and microseconds
mktime
Get a UNIX timestamp
strtotime
Parse any English text datetime description into a UNIX timestamp
time
Returns the current UNIX timestamp
9.2 Processing date and time
9.2.1 Get the current date and time: date() function, usage:
date(string format,int timestamp)
This function will return a string generated by the timestamp parameter according to the specified format. The parameter timestamp is optional. If omitted, the current time is used. The format parameter allows developers to output the time and date in the format they specify.
date_default_timezone_set(PRC); //Set Beijing time.
1. Year-month-day
echo date('Y-m-j'); //Example: 2007-02-6
echo date('y-n-j'); //Example: 07-2-6
An uppercase Y represents a four-digit year, while a lowercase y represents a two-digit year;
Lowercase m represents the number of the month (with a leading), while lowercase n represents the number of the month without the leading.
echo date('Y-M-j'); //Example: 2007-Feb-6
echo date('Y-m-d'); //Example: 2007-02-06
Uppercase M represents the 3 abbreviated characters of the month, while lowercase m represents the number of the month (with leading 0);
There is no uppercase J, only lowercase j represents the day of the month, without the leading o; if a leading month is required, use a lowercase d.
echo date('Y-M-j'); //Example: 2007-Feb-6
echo date('Y-F-jS'); //Example: 2007-February-6
Capital M represents the 3 abbreviated characters of the month, while capital F represents the full English letter of the month. (no lowercase f)
Capital S represents the suffix of the date, such as "st", "nd", "rd" and "th", depending on the date number.
Summary:
The year can be represented by uppercase Y and lowercase y;
Months can be represented by uppercase F, uppercase M, lowercase m and lowercase n (two ways to represent characters and numbers respectively);
Lowercase d and lowercase j can be used to represent the day, and uppercase S represents the suffix of the date.
2. Hour:minute:second
By default, PHP interprets the displayed time as "Greenwich Mean Time", which is 8 hours different from our local time.
echo date('g:i:s a'); //Example: 5:56:57 am
echo date('h:i:s A'); //Example: 05:56:57 AM
A lowercase g indicates a 12-hour clock without leading 0s, while a lowercase h indicates a 12-hour clock with leading 0s.
When using the 12-hour clock, it is necessary to indicate morning and afternoon. Lowercase a represents lowercase "am" and "pm", and uppercase A represents uppercase "AM" and "PM".
echo date('G:i:s');14:02:26
Capital G represents the hour in 24-hour format, but without leading; use capital H to represent hour in 24-hour format with leading
Summary:
The letter g represents the hour without leading, and the letter h represents the hour with leading;
Lowercase g and h represent the 12-hour format, while uppercase G and H represent the 24-hour format.
3. Leap year, week, day
Capital L indicates whether this year is a leap year, Boolean value, returns 1 if true, otherwise 0;
The lowercase l represents the full English word for the day of the week (Tuesday);
Instead, use a capital D to represent the 3-character abbreviation of the day of the week (Tue).
echo date('w'); //Example: Today's week: 2
echo date('W'); //Example: This week is the 06th week of the year
The lowercase w represents the day of the week, and the numeric form represents
Capital W represents the number of weeks in the year
echo date('t'); //Example: This month has 28 days
echo date('z'); //Example: Today is the 36th day of this year
Lowercase t represents the number of days in the current month
Lowercase z indicates what day of the year today is
4. Others
echo date('T'); //Example: UTC
A capital T represents the server’s time locale
echo date('I'); //Example: 0
Capital I means to determine whether the current daylight saving time is, if true, return 1, otherwise 0
echo date('U'); //Example: 1170769424
A capital U represents the total number of seconds from January 1, 1970 to the present, which is the UNIX timestamp of the Unix time epoch.
echo date('c'); //Example: 2007-02-06T14:24:43+00:00
Lowercase c represents an ISO8601 date, the date format is YYYY-MM-DD, the letter T is used to separate the date and time, the time format is HH:MM:SS, and the time zone is represented by the offset from Greenwich Mean Time (GMT).
echo date('r'); //Example: Tue, 06 Feb 2007 14:25:52 +0000
A lowercase r indicates the RFC822 date.
9.2.2 Obtain date information: getdate() function
Syntax:
Array getdate(int timestamp)
This function returns date and time information in the form of an array. If there is no timestamp, the current time shall prevail. The description of the associative array elements returned by this function is shown in Table 9-2:
Table 9-2: Description of associative array elements returned by the getdate() function
Element
Say Ming
seconds
Seconds, return value 0~59
minutes
Minutes, the return value is 0~59
hours
Hours, the return value is 0~23
mday
The day of the month, the return value is 1~31
wday
The day of the week, the return value is 0 (Sunday) ~ 6 (Saturday)
mon
Month number, return value is 1~12
year
The complete year represented by 4 digits, return value plus 2000 or 2008
yday
The day of the year, return value 0~365
weekday
The complete text representation of the day of the week, the return value is Sunday~Saturday
month
The complete text representation of the month, the return value is January~December
0
Returns the number of seconds since the UNIX epoch
Example:
$arr = getdate();
echo $arr[year]."-".$arr[mon]."-".$arr[mday]."";
echo $arr[hours].":".$arr[minutes].":".$arr[seconds]."".$arr[weekday];
echo "
";
echo "Today is the $arr[yday]th of year";
?>
Effect:
9.3 UNIX timestamp
The timestamp is the creation, modification, and access time in the file attributes. Digital time stamp service (DTS) is one of the web website security services that can provide security protection for the date and time information of electronic files.
9.3.1 What is timestamp
The timestamp is an encrypted credential document, which consists of 3 parts:
² Files that need to be timestamped are encrypted using Hash encoding to form a summary.
² DTS accepts the date and time information of the file.
² Encrypt received DTS files.
The digital time is added by the certification unit DTS, based on the time when DTS receives the file.
The working principle of timestamp is to convert the time value into an encrypted value through other encryption methods. When the time changes, the encrypted value also changes.
The advantage of the timestamp is that the changing encrypted value prevents the value from being stolen and illegally reused, which also plays the role of encryption. Timestamps mainly rely on time and generate a unique value within an agreed period of time.
9.3.2 Get local timestamp: mktime() function
Syntax:
int mktime(int hour, int minute, int month, int day, int year, int [is_dst])
Table 9-3: Parameter description of mktime() function
Parameter
Say Ming
hour
Hours
minute
Minutes
second
Number of seconds (within one minute)
month
Number of months
day
Number of days
year
Year number
is_dst
The parameter is_dst can be set to 1 during daylight saving time, or 0 if not; if not sure whether it is daylight saving time, set to -1 (default value)
Note: The typical range of valid timestamps is December 13, 1901 20:45:54 GMT to January 19, 2038 03:13:07 (this range conforms to the minimum and maximum values of 32-bit signed integers) . In Windows systems, this range is limited to January 1, 1970 to January 19, 2038.
Example:
echo "The timestamp returned by the mktime function:".mktime()."
";
echo "The current date is:".date("Y-m-d",mktime())."
";
echo "The current time is:".date("H:i:s",mktime());
?>
Effect:
9.4 System time zone setting
During the learning process, many students found that the time obtained through the date() function is different from the local time. This is because PHP5 has rewritten the date() function. Therefore, the current date and time function is 8 hours less than the system time. . The default setting in the PHP language is standard Greenwich Time (that is, the zero time zone is used).
There are two main ways to change the time zone setting in PHP language:
1. Modify the settings in the php.ini file, find the;date.timezone = option under [date], change this item to date.timezone=Asia/Hong_Kong, and then restart the apache server.
2. In the application, add the following function before using the time and date function:
date_default_timezone_set(“Asia/Hong_Kong”);
After the setting is completed, the date() function can be used normally, and the time difference problem will no longer occur.
9.5 Date and time problems encountered in time development
9.5.1 Compare the size of two times
In actual development, we often encounter the problem of judging the size of two times. Times in PHP cannot be directly compared. Therefore, first output the time in timestamp format, and then compare. This is a commonly used method.
There are two functions that can achieve this function. The strtotime() function is used here, which can parse the date and time description of any English text into a UNIX timestamp. The syntax of this function is:
int strtotime(string time, int now)
This function has two parameters. If the format of the parameter time is an absolute time, the now parameter has no effect; if the format of the parameter time is a relative time, then the corresponding time is provided by the parameter now. If the parameter now is not provided, the corresponding time is the current time. If parsing fails, -1.
is returned
Example:
$time1 = date("Y-m-d H:i:s"); //Get the current time
$time2 = "2008-2-3 16:30:00"; //Set a time for variable $time2
echo "The time of variable/$time1 is: ".$time1."
"; //Output two time variables
echo "The time of variable/$time2 is: ".$time2."
";
If (strtotime($time1)-strtotime($time2)<0) { //Compare two times
echo "/$time1 is earlier than /$time2"; //If time1-time2<0, it means that the time of time1 is first
}else{
echo "/$time2 is earlier than /$time1"; // Otherwise, it means that time2 is earlier
}
?>
Effect:
9.5.2 Calculate the difference between two dates
In addition to comparing the size of two dates, the strtotime() function can also accurately know the difference between two dates. The following uses a small countdown program to explain to students how to use the strtotime() function to calculate the difference between two dates.
$time1 = strtotime(date( "Y-m-d H:i:s"));
$time2 = strtotime("2008-2-3 17:10:00");
$time3 = strtotime("2008-8-8");
$sub1 = ceil(($time2 - $time1) / 3600); $sub1 = ceil(($time2 - $time1) / 3600); //60 * 60
$sub2 = ceil(($time3 - $time1) / 86400); //60 * 60 * 24
echo "There are still $sub1 hours before the holiday!!!" ;
echo "
";
echo "There are still $sub2 days until the opening of the Beijing Olympics!!!";
?>
Effect:
9.5.3 Calculate the running time of the page script
When browsing websites, search engines are often used. When searching for information, careful users will find that at the bottom of the search results, there is usually the words "Search time is...seconds".
The microtime() function is used here, which returns the current UNIX timestamp and microseconds. Returns a string in the format msec sec, where sec is the current UNIX timestamp and msec is the number of microseconds. The format of this function is:
string microtime(void)
Let’s calculate the running time of the above example, the code is as follows:
function run_time()
{
List($msec, $sec) = explode(" ", microtime());
Return ((float)$msec + (float)$sec);
}
$start_time = run_time();
$time1 = strtotime(date( "Y-m-d H:i:s"));
$time2 = strtotime("2008-2-3 17:10:00");
$time3 = strtotime("2008-8-8");
$sub1 = ceil(($time2 - $time1) / 3600); $sub1 = ceil(($time2 - $time1) / 3600); //60 * 60
$sub2 = ceil(($time3 - $time1) / 86400); //60 * 60 * 24
echo "There are still $sub1 hours before the holiday!!!" ;
echo "
";
echo "There are still $sub2 days until the opening of the Beijing Olympics!!!";
$end_time = run_time();
?>
The example runs in seconds