PHP Date and Time _php tutorial

Source: Internet
Author: User
Tags echo date php language
PHP provides a large number of built-in functions that enable developers to work on time, greatly improving productivity. Today we will present some common PHP date and time functions as well as date and time processing for the participants.

9.1 Commonly used date and time processing functions

Table 9-1: Commonly used date and time processing functions




Validates the time function, determines whether the time is valid, returns true correctly, or returns false


Gets the default time zone used by the script datetime function


Set the default time zone for datetime functions


Format a local time/date


Get Date/Time information


Get current time


Get local time


Returns the current timestamp and the number of microseconds


Get a Unix timestamp


Resolves a datetime description of any English text to a UNIX timestamp


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)

The function returns a string that is generated by the parameter timestamp in the specified format. Where the parameter timestamp is optional and if omitted, the current time is used. The format parameter allows the developer to output a time date in the form that it specifies.

Date_default_timezone_set (PRC); Set the GMT.

1. Year-month-day

echo Date (' y-m-j '); Example: 2007-02-6

echo Date (' y-n-j '); Example: 07-2-6

Uppercase Y represents the year four digits, while lowercase y represents the two digits of the year;

Lowercase m represents the number of months (with leading), while lowercase n indicates no leading month number.

echo Date (' y-m-j '); Example: 2007-feb-6

echo Date (' y-m-d '); Example: 2007-02-06

The uppercase M represents the 3 abbreviated characters of the month, while the lowercase m represents the number of the month (with leading 0);

J with no uppercase, only lowercase J indicates the date of the month, no leading o, or lowercase D if a month with a leading is required.

echo Date (' y-m-j '); Example: 2007-feb-6

echo Date (' Y-f-js '); Example: 2007-february-6

Uppercase M represents the 3 abbreviated characters of the month, while uppercase F indicates the full written English of the month. (No lowercase f)

Uppercase S represents the suffix of the date, such as "St", "nd", "rd", and "th", depending on the date number.


Indicates that the year can be in uppercase Y and lowercase y;

Indicates that the month can be in uppercase F, uppercase M, lowercase m, and lowercase n (two ways of representing characters and numbers, respectively);

Indicates that the day can be in lowercase d and lowercase j, and uppercase s represents the suffix of the date.

2, Hours: minutes: seconds

By default, the PHP interpretation is displayed as "Greenwich Mean Time", which differs from our local time by 8 hours.

echo Date (' g:i:s a '); Example: 5:56:57 am

echo Date (' H:i:s A '); Example: 05:56:57 AM

The lowercase g represents a 12-hour system without a leading 0, while the lowercase h indicates a 12-hour system with a leading 0.

When using the 12-hour system, it is necessary to indicate that in the afternoon, lowercase a represents the lowercase "am" and "PM", and uppercase a denotes uppercase "AM" and "PM".

echo Date (' g:i:s '); 14:02:26

Uppercase G denotes 24-hour hours, but without preamble, and uppercase H for leading 24-hour hours


The letter g means the hour without leading, the letter H denotes the hour with the preamble;

lowercase g, h for 12-hour system, uppercase G, h for 24-hour system.

3, Leap year, week, day

Uppercase L Indicates whether this year is a leap years, a Boolean value that returns 1 for true, otherwise 0;

Lowercase L Indicates the day of the week in English full write (Tuesday);

Instead, use uppercase D to denote the 3-character abbreviation (TUE) of the day of the week.

echo Date (' W '); Example: Today's week: 2

echo Date (' W '); This week is the No. 06 week of the Year

The lowercase w represents the day of the week, and the numeric representation

Uppercase W indicates the number of weeks in a year

echo Date (' t '); Example: This month is 28 days

echo Date (' Z '); Today is the 36th day of this year

Lowercase t indicates the current month and how many days

Lowercase z indicates that today is the first day of the year

4, other

echo Date (' T '); Example: UTC

Capital T indicates the server's time zone setting

echo Date (' I '); Example: 0

Uppercase I indicates whether the current is daylight saving time, returns 1 for true, otherwise 0

echo Date (' U '); Example: 1170769424

The capital U represents the total number of seconds from January 1, 1970 to the present, which is the UNIX timestamp for the Unix time era.

echo Date (' C '); Example: 2007-02-06t14:24:43+00:00

Lowercase C represents the ISO8601 date, the date format is YYYY-MM-DD, the letter T is used to interval the date and time, the time format is HH:MM:SS, and the time zone is represented by the deviation of Greenwich Mean Time (GMT).

echo Date (' R '); Example: Tue, Feb 2007 14:25:52 +0000

The lowercase R represents the RFC822 date.

9.2.2 Get date information: getdate () function


Array getdate (int timestamp)

The function returns datetime information in the form of an array, whichever is the current time if there is no timestamp. The description of the associated array element returned by the function is shown in table 9-2:

Table 9-2:getdate () function returns an associative array element description




seconds, return value 0~59


Minutes with a return value of 0~59


Hours, the return value is 0~23


The day ordinal of the month, the return value is 1~31


The first day of the week, the return value is 0 (Sunday) to (Saturday)


Month number, return value is 1~12


4-digit full year, return value plus 2000 or 2008


The first day of the year, the return value 0~365


The full text representation of the day of the week, with a return value of Sunday~saturday


Full text representation of the month with a return value of January~december


Returns the number of seconds since the Unix era


$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];



9.3 Unix Timestamp

The timestamp is the creation, modification, and access time in the file properties. Digital time stamp service, DTS, is one of the Web site security services items that provide the security of date and time information for electronic files.

9.3.1 What is a timestamp

The timestamp is a document that has been encrypted and formed, and consists of 3 parts:

² files that need to add timestamps are encrypted with hash code to form a digest.

²dts Accept the date and time information for the file.

² Encrypt the accepted DTS files.

The digital time is added by the Authentication unit DTS, which is based on the time that DTS received the file.

The function of time stamp is to convert the value of time into an encrypted value by other encryption method, and the value of encryption will change after time change.

The advantage of the timestamp is that the variable encryption value prevents the value from being stolen illegally, and it plays the role of encryption. Timestamps are mainly dependent on time and produce a unique value for a specified period of time.

9.3.2 get local timestamp: mktime () function


int mktime (int hour, int minute, int month, int day, int year, int [IS_DST])

Table 9-3:mktime () function parameter description




Number of hours


Number of minutes


Number of seconds (within one minute)


Number of months




Number of years


The parameter is_dst can be set to 1 for daylight saving time, if not set to 0, or 1 (default) if it is not determined if daylight saving time is set.

Note: A valid timestamp typically ranges from GMT December 13, 1901 20:45:54~2038 January 19 03:13:07 (this range conforms to the minimum and maximum values of 32-bit signed integers). This range is limited in Windows systems from January 1, 1970 ~2038 January 19.


echo "Mktime function returns the timestamp:". Mktime (). "


echo "Current date is:". Date ("Y-m-d", Mktime ()). "


echo "The current time is:". Date ("H:i:s", Mktime ());



9.4 System time zone settings

Many students find that the time taken by the date () function is different from the local time in the learning process because PHP5 has rewritten the date () function, so the current datetime function is 8 hours less than the system time. The standard GMT is set by default in the PHP language (that is, the zero zone is used).

There are two main ways to change the time zone settings in the PHP language:

1. Modify the settings in the php.ini file, locate the [date], Date.timezone = option, modify the entry to Date.timezone=asia/hong_kong, and then restart the Apache server.

2. In the application, add the following function before using the time-date function:

Date_default_timezone_set ("Asia/hong_kong");

When the settings are complete, the date () function will work as expected and no more slack will occur.

9.5 Date and time issues encountered during development

9.5.1 Compare the size of two times

In the actual development often encountered to determine the size of two times, PHP time is not directly to the comparison. Therefore, the first time to output a timestamp format, and then compare, this is a common method.

There are two functions that can be implemented, using the Strtotime () function, which resolves the datetime description of any English text to a Unix timestamp. The syntax for this function is:

int Strtotime (string time, int now)

The function has two parameters. If the format of the parameter time is absolute, then the now parameter does not work, and if the parameter time is formatted as a relative time, then its corresponding timing is provided by the parameter, and if no parameter is present, the corresponding time is the current time. If the parsing fails, 1 is returned.


$time 1 = Date ("y-m-d h:i:s"); Get current time

$time 2 = "2008-2-3 16:30:00"; Set a time for the variable $time2

echo "Variable/$time 1 of the time:". $time 1. "
"; Output of two time variables

echo "Variable/$time 2 of the time:". $time 2. "

if (Strtotime ($time 1)-strtotime ($time 2) <0) {//Compare two time

echo "/$time 1 earlier than/$time 2"; If time1-time2<0 indicates that time1 time is in front


echo "/$time 2 earlier than/$time 1"; Otherwise, the time2 time is in front




9.5.2 Calculate the difference of two dates

The Strtotime () function can also accurately know the difference between two dates, in addition to the size of the two dates. Below is a countdown applet to explain how to use the Strtotime () function to calculate the difference between two dates.

$time 1 = strtotime (Date ("y-m-d h:i:s"));

$time 2 = strtotime ("2008-2-3 17:10:00");

$time 3 = strtotime ("2008-8-8");

$sub 1 = ceil ($time 2-$time 1)/3600); 60 * 60

$sub 2 = ceil ($time 3-$time 1)/86400); 60 * 60 * 24

echo "$sub 1 hours!!! from the holiday";

echo "


echo "From the opening of the Beijing Olympic Games and $SUB2 days!!!";



9.5.3 calculating the run time of a page script

When browsing the site, often use the search engine, in the search for information, careful users will find that at the bottom of the search results, generally have "search time for ..." Seconds "of the word.

The Microtime () function is used here to return the current UNIX timestamp and the number of microseconds. Returns a string formatted as msec sec, where the SEC is the current Unix timestamp and msec is the number of microseconds. The format of the function is:

String Microtime (void)

Let's calculate the elapsed 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 ();

$time 1 = strtotime (Date ("y-m-d h:i:s"));

$time 2 = strtotime ("2008-2-3 17:10:00");

$time 3 = strtotime ("2008-8-8");

$sub 1 = ceil ($time 2-$time 1)/3600); 60 * 60

$sub 2 = ceil ($time 3-$time 1)/86400); 60 * 60 * 24

echo "$sub 1 hours!!! from the holiday";

echo "


echo "From the opening of the Beijing Olympic Games and $SUB2 days!!!";

$end _time = Run_time ();


The run time of the example is seconds true techarticle PHP provides a large number of built-in functions that enable developers to work on time, greatly improving productivity. We will introduce some common PHP date and time letters to our students today ...

  • 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: 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.