PHP Date Function Dates

Source: Internet
Author: User
Tags explode expression first string functions getdate variables split string format

Use the function date () to implement the

displayed in the format: year-month-day hours: minutes: sec
Related Time parameters:
A-"AM" or "PM"
A-"AM" or "PM"
D-A few days, two digits, if less than two digits before the 0; such as: "01" to "31"
D-Days of the week, three English letters; such as: "Fri"
F-month, full name in English; such as: "January"
Hours of h-12 hours; such as: "01" to "12"
H-24 hours of hours; such as: "00" to "23"
G-12 hours, less than two-bit not to fill 0; such as: "1" to 12 "
G-24 hours of hours, less than two to fill 0; such as: "0" to "23"
I-minute; such as: "00" to "59"
J-A few days, two digits, if less than two digits do not fill 0; such as: "1" to "31"
L-Days of the week, full name in English; such as: "Friday"
M-month, two digits, if less than two digits in front of the 0; such as: "01" to "12"
N-month, two digits, if less than two digits will not fill 0; such as: "1" to "12"
M-month, three English letters; such as: "The"
S-seconds; such as: "00" to "59"
S-word tail plus English ordinal number, two English letters; such as: "th", "nd"
T-Specifies the number of days of the month; such as: "28" to "31"
U-Total number of seconds
W-Number of days of the week, such as: "0" (Sunday) to "6" (Saturday)
Y-year, four digits; such as: "1999"
Y-year, two digits; such as: "99"
Z-the day ordinal of the year; such as: "0" to "365"
You can set the displayed content freely, connect the symbol or display position, such as date ("m-d H") or date ("Dmy"). Date processing in PHP > etc
Add Time: 2004-12-18 17:35:22 size: KB read: Date processing in 1405PHP
Posted: Xiaxia Date: 2004-05-26 Views: 9
I'm trying to write a help-processing system in PHP. I found that I had to know how long it had been since I had finished working on the last client. When I used to solve this problem with ASP is quite simple, the ASP has the corresponding function DateDiff can give two days period interval How many months, how many days and how many seconds. When I searched through the PHP manual I found that PHP did not have a similar function.
This article contains the following elements:
1, get the current date and time-how many ways do we have?
2, change the date display mode-date and time display form
3, the conversion of the current date is a Unix timestamp value
4. Change Date
A. Increased time
B. Minus the time
C. Finding the interval between two dates
5. Add DateAdd function to PHP
6. Add DateDiff function to PHP
* * Get the current date and time
In Unix, time is represented by the number of seconds that have elapsed since 0 o'clock January 1, 1970, which is called the Unix timestamp (Unix Epoch).
If we have such a section of code:
echo Time ();
Returns a value of 958905820
And the time for this is May 21, 2000 12:43.
You might say it's pretty good. When it doesn't help me or just a little help. In PHP, a date-processed function must use the timestamp value returned by Time (). Also, because PHP uses the same timestamp value in both UNIX and Windows systems, this allows you to migrate between different systems without modifying the code. Another advantage is that the time () function returns an integer that you can save as an integer or text field without having to use a special date/Time field.
You've got a basic idea of the time stamp value of Unix, so let's now show what it's actually used for.
Change the way the date is displayed-the date and time display form
PHP provides two ways to convert the timestamp value of UNIX into useful data. The first one is the date () function. This function has two parameters-the first string is used to set the format you want to return, and the second is the time stamp value for UNIX.
The format string displays the date and time of the format you want to see through some simple special formatting characters. Suppose you want the date to display "18h01 Sunday may" in such a format.
We need to use a special format character for each part of the string, which you can find in the PHP manual from the date and time library. There are a number of special format characters that they represent, like the English name of the week, the month, 2-bit or 4-digit years, whether it is morning (AM) or PM (PM), and others. The special characters we need for this example are:
' H '-24-hour hours
' I '-minutes
' L '-the English full name of the week
' d '-day of the month
' F '-the full name of the month in English
So our format string is "Hhi l D F", and the PHP code is:
echo Date ("Hhi l D F", Time ());
When we execute this code, we find that the results we get are:
180609 Sunday May
The results look a little odd. Let's check the PHP manual again, which is what ' H ' stands for 12-hour hours. Again, this proves the truth: "The computer only does what you tell it to do, not what you want it to do." We have two choices. The first is to use the escape character "" Before H:
echo Date ("Hhi l D F", Time ());
We get this result:
18h12 Sunday May
That's exactly what we want. But if we need to include the date and time in a very complex sentence, do we need to use the escape character for each character?
The answer, of course, is no. We use another function strftime ().
Strftime () has two benefits. The first benefit is that we are not covered in this article-if you use the setlocale () function, you can get the name of the month of the corresponding language by strftime. Another advantage is that you can include special date and time formatting characters in your string. This also means that whether or not you want to learn all the special formatting characters of the date () function, you must learn a whole set of completely different formatting characters.
The way Strftime () works is no different from date (), except that a percent semicolon must be added before a specially formatted character. If you use the Strftime () function, the preceding example has the following code:
Echo strftime ("%hh%m%A%d%b", Time ());
The results are:
18h24 Sunday May
This may seem to simplify the complex, but consider if you need to display "Today's is Sunday 2000." The time was somewhere close to 18h24. "I think using the date () function is no doubt annoying.
In the beginning, I mentioned that there are two ways we can get useful data from the UNIX timestamp value. We have just learned about date () and strftime (). Another getdate (). This function requires only the timestamp value of Unix as an argument, and the return value of the function is an array of dates and times.
Here is an example:
$date _time_array = getdate (Time ());
echo $date _time_array["weekday"];
The result returned is:
In addition to "weekday", the other parts of the array are:
"Seconds" – seconds
"Minutes" – divided
"Hours" – hours
"Mday"-Day of the month
"Wday"-Day of the Week (number)
"Mon"-month (number)
"Year" –
"Yday"-the first day of the year (number)
"Month"-month full name
We can now get an easily identifiable date and time. What about the rest?
* * Convert the current date to the time stamp value of Unix
Usually you have to deal with data in some date or time format. Open an Access database for m$, all dates are stored in YYYY/MM/DD format, and the current date is 2000/05/27. The Mktime () function converts a time to a time stamp value of UNIX.
The format of the function is: int mktime (int hour, int minute, int second, int month, int day, int, int [is_dst]);
From left to right you must provide hours, minutes, seconds, months, days and years. The last parameter is used to specify whether you are in daylight saving time, this parameter is optional, so we will ignore it.
The code is as follows:
Echo mktime (0, 0,0, 5, 27,2000);
I set it to 0 because I don't know the hours, minutes, and seconds and the parameters must be filled in. Setting to 0 means that the time is midnight.
$access _date = "2000/05/27";
The explode () function decomposes another string using a string as a boundary. This example $access_date through the string "/" to decompose
$date _elements = Explode ("/", $access _date);
$date _elements[0] = 2000
$date _elements[1] = 5
$date _elements[2] = 27
Echo mktime (0, 0,0, $date _elements [1], $date _elements[2], $date _elements [0]);
Let's look at a situation that is more complicated than getting a date from an Access database, we get a date and time in the following format: 2000/05/27 02:40:21 PM
A string from Access
$date _time_string = "2000/05/27 02:40:21 PM";
Break a string into 3 parts-date, time, and morning/afternoon
$dt _elements = Explode ("", $date _time_string);
Decomposition date
$date _elements = Explode ("/", $dt _elements[0]);
Decomposition time
$time _elements = Explode (":", $dt _elements[1]);
If it's afternoon, we'll increase the time by 12 hours to get the 24-hour system.
if ($dt _elements [2]== "PM") {$time _elements[0]+=12;}
Output results
Echo mktime ($time _elements [0], $time _elements[1], $time _elements[2], $date _elements[1], $date _elements[2], $date _ Elements[0]);
* * Modified Date
Sometimes we need to know what time it is 6 hours later, the date 35 days ago, or how many seconds have elapsed since the last time you played Quake3. We already know how to use the Mktime () function to get the timestamp value of a UNIX from a separate date and time. What should we do if we need a Unix timestamp value that is not the current date and time? Here are some exercises to help explain what we are going to do later.
As you can see earlier, Mktime () uses the following parameters: hours, minutes, seconds, months, days, and years. To think of the second section, the GETDATE () function can get these parameters for us.
Put the current timestamp value inside an array
$timestamp = time ();
Echo $timestamp;
echo "P";
$date _time_array = getdate ($timestamp);
Re-generating the Unix timestamp value with the Mktime () function
$timestamp = mktime ($date _time_array ["hours"], $date _time_array["Minutes"], $date _time_array["seconds"], $date _time _array ["Mon"], $date _time_array["Mday"], $date _time_array["Year"]);
Echo $timestamp;
There seems to be some confusion. I'll use some variables to make the above program look easier to understand.
Put the current timestamp value inside an array
$timestamp = time ();
Echo $timestamp;
echo "P";
$date _time_array = getdate ($timestamp);
$hours = $date _time_array["Hours"];
$minutes = $date _time_array["Minutes"];
$seconds = $date _time_array["seconds"];
$month = $date _time_array["Mon"];
$day = $date _time_array["Mday"];
$year = $date _time_array["year"];
Re-generating the Unix timestamp value with the Mktime () function
$timestamp = Mktime ($hours, $minutes, $seconds, $month, $day, $year);
Echo $timestamp;
Now we put the timestamp value generated by GETDATE () into the corresponding name variable, so the code becomes relatively easy to read and understand. Now if we need to add 19 hours to the current time, we use $hours+19 instead of the $hours in the Mktime () function. Mktime () will automatically transfer the time to the next day for us.
Put the current timestamp value inside an array
$timestamp = time ();
Echo strftime ("%hh%m%A%d%b", $timestamp);
echo "P";
$date _time_array = getdate ($timestamp);
$hours = $date _time_array["Hours"];
$minutes = $date _time_array["Minutes"];
$seconds = $date _time_array["seconds"];
$month = $date _time_array["Mon"];
$day = $date _time_array["Mday"];
$year = $date _time_array["year"];
Re-generating the Unix timestamp value with the Mktime () function
Increase by 19 hours
$timestamp = mktime ($hours + $minutes, $seconds, $month, $day, $year);
Echo strftime ("%hh%m%A%d%b", $timestamp);
echo "Br~e after adding hours";
After running get:
14h58 Saturday June
09h58 Sunday June
~e after adding hours
The same is true for reducing time-you just need to reduce the value of the corresponding variable.
It is also very simple to get the difference between two different time values. All you have to do is convert two time values to UNIX timestamp values and subtract the two. The difference between the two is the number of seconds that are separated by two of times. Other algorithms can quickly convert seconds to days, hours, minutes, and seconds.
* * Add DateAdd function to PHP
As I said at the beginning of the article, the reason for writing this article is that I can't find an ASP-like DateDiff function in PHP. After introducing how PHP handles dates and times, let's migrate the two functions commonly used in ASP to PHP. The first function is DateAdd.
According to the documentation for VBScript, the DATEADD (interval,number,date) function is defined as "returns the date when the specified time interval has been added." ”
Inetrval is a numeric expression that represents the interval of time that you want to add, such as a minute or day, or number, which represents the amount of time interval to add;
Interval (time interval string expression) can be any of the following values:
YYYY year
Q Quarter Quarter
M Month Month
Y Day of the Year
D Day Days
W weekday days in a week
WW Week of year
H Hour Hours
s second sec
The functions of W, Y and D are exactly the same, that is, add a day to the current date, Q plus 3 months, WW plus 7 days.
function DateAdd ($interval, $number, $date) {
$date _time_array = getdate ($date);
$hours = $date _time_array["Hours"];
$minutes = $date _time_array["Minutes"];
$seconds = $date _time_array["seconds"];
$month = $date _time_array["Mon"];
$day = $date _time_array["Mday"];
$year = $date _time_array["year"];
Switch ($interval) {
Case "yyyy": $year + + $number; Break
Case "Q": $month + + ($number *3); Break
Case "M": $month + + $number; Break
Case "Y":
Case "D":
Case "W": $day + + $number; Break
Case "WW": $day + + ($number *7); Break
Case "H": $hours + + $number; Break
Case "n": $minutes + + $number; Break
Case "s": $seconds + + $number; Break
$timestamp = Mktime ($hours, $minutes, $seconds, $month, $day, $year);
return $timestamp;}
We can save the above code as a file, and then run the following code:
Include (' ');
$temptime = time ();
Echo strftime ("%hh%m%A%d%b", $temptime);
$temptime = DateAdd ("n", M, $temptime);
echo "P";
Echo strftime ("%hh%m%A%d%b", $temptime);
We will get:
15h41 Saturday June
16H31 Saturday June
Add DateDiff function to PHP
Now that DateAdd is finished, what about DateDiff?
According to the document, the DateDiff (INTERVAL,DATE1,DATE2) function is defined as "returns the time interval between two dates."
The use of the intervals parameter is the same as in the DateAdd function. To avoid overly complex considerations, we decided to ignore other complex parameters in the DateDiff function in VBScript, that is, its two optional parameter variables [firstdayofweek[, FirstWeekOfYear]] (They are used to determine whether the first day of the week is Sunday or Monday and the first week of the year.) And we only allow the intervals to have the following five values: "W" (week), "D" (Day), "H" (hour), "n" (minutes), and "s" (seconds).
Let ' s-what we can come up with: The following code is what we need:
Function DateDiff ($interval, $date 1, $date 2) {
To get the number of seconds between two dates
$timedifference = $date 2-$date 1;
Switch ($interval) {
Case "W": $retval = Bcdiv ($timedifference, 604800); Break
Case "D": $retval = Bcdiv ($timedifference, 86400); Break
Case "h": $retval = Bcdiv ($timedifference, 3600); Break
Case "n": $retval = Bcdiv ($timedifference, 60); Break
Case "s": $retval = $timedifference; Break
return $retval;}
Save the above code as a file, and then run the following code:
Include (' ');
Include (' ');
$currenttime = time ();
echo "Current time:". Strftime ("%hh%m%A%d%b", $currenttime). " BR ";
$newtime = DateAdd ("n", M, $currenttime);
echo "Time plus minutes:". Strftime ("%hh%m%A%d%b", $newtime). " BR ";
$temptime = DateDiff ("n", $currenttime, $newtime);
echo "Interval between two times:". $temptime;
If all goes well, you can see the following results:
Current TIME:16H23 Saturday June
Time plus minutes:17h13 Saturday June
Interval between two times:50
If you run PHP on a UNIX machine, you must compile PHP to support the BC High precision function. You must download the BC Library from the following address and unzip it to the root of PHP4, recompile PHP, and add the--enable-bcmath option when compiling. (see PHP4 in Readme.bcmath) for more information. PHP4 's version of Windows does not require any patching to directly use BC High-precision functions.
Now that you have the function to process the date and time, the rest is how to apply it to your PHP program.
PHP Time Display Example
Add Time: 2004-12-18 17:22:53 Size: 1 KB read times: 1564
The first type: simple (for study)
$today =date ("y-m-d g:i:s");
echo "

The second type:
Format time
Function formattime ($time, $type = "1") {
Switch ($type) {
Case 1; #2002 -06-0418:58 Tuesday
Return Date ("Y.m.d h:i", $time). "". Date ("L", $time). "";
Case 2; #June 2002
Return Date ("M Y", $time);
Case 3; #2002-06-04 18:58
Return Date ("Y.m.d h:i", $time);
Case 4; #06 -04 AM
Return Date ("M-d A", $time);
Case 5; #06-04 18:58
Return Date ("M.D h:i", $time);
I don't know what the result would be for a comparison of two dates stored in string format, such as ' 2007-07-12′ ' 2007-06-27′, what is the best way to compare this date? It's about size.
Leehao July 17th, 2006 1:33 AM
/* Date Comparison * *
$Date _1= "2007-07-12";
$Date _2= "2007-06-27";
First, use the Explode function to split the string.
Explode ("This quotation mark inside is the condition to come, change: will use: To split the string, can apply to many aspects to go", after the string to be split)
$Date _explode_1=explode ("-", $Date _1);
$Date _explode_2=explode ("-", $Date _2);
After splitting the string, we calculate the time by using the Mktime function,
It must be explained that the time calculated by mktime is counted in seconds.
The back is simple, you can see the manual, which is very detailed
$Day _1=mktime (0,0,0, $Date _explode_1[1], $Date _explode_1[2], $Date _explode_1[0]);
$Day _2=mktime (0,0,0, $Date _explode_2[1], $Date _explode_2[2], $Date _explode_2[0]);
$Days =round (($Day _1-$Day _2)/3600/24);
echo "You want the result is $Days day Oh";
How do I get the date 90 days later
Add Time: 2004-12-18 18:09:53 Size: 1 KB read times: 158
Get today's time information
$Y =date (Y);
$m =date (m);
$d =date (d);
$m for the month, $d for the day, $Y for the year, "+" number after the "-" can get the number of days before the date, "Y-M-month D-Day", just show the format, you can change to "y-m-d",
$out _date1=date ("Y-year m-month D-Day", Mktime (0,0,0, $m, $d +7, $Y));//a week later
$out _date2=date ("Y-year m-month D-Day", Mktime (0,0,0, $m, $d +14, $Y));//Two weeks later
$out _date3=date ("Y-year m-month D-Day", Mktime (0,0,0, $m +1, $d, $Y));//One months later
$out _date4=date ("Y-year m-month D-Day", Mktime (0,0,0, $m +2, $d, $Y));//Two months later
$out _date5=date ("Y-year m-month D-Day", Mktime (0,0,0, $m +3, $d, $Y));//Three months later
$out _date6=date ("Y-year m-month D-Day", Mktime (0,0,0, $m +6, $d, $Y));//Six months later
$out _date7=date ("Y-year m-month D-Day", Mktime (0,0,0, $m, $d, $Y + 1));//One year later

echo Date ("Ymd", Time () + 90*86400);

echo Date ("Y-m-d", Strtotime ("2004-10-26 +90day"));
Date ("Y-m-d", Strtotime ("+90 Day"));

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