There are no date subtraction functions in PHP

Source: Internet
Author: User
Tags explode expression first string functions getdate variables string variable
The direct subtraction of functions is not correct, you need to do this:

* * 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 ("H\hi 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:
Sunday
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);
Now
$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
N-minute
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 dateadd.inc file, and then run the following code:
?
Include (' Dateadd.inc ');
$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 datediff.inc file, and then run the following code:
?
Include (' Datediff.inc ');
Include (' Dateadd.inc ');
$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 http://www.php.net/extra/number4.tar.gz 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.


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