A collection of date processing methods in PHP _php tutorial

Source: Internet
Author: User
Tags echo date first string
This article contains the following content:
1. Get the current date and time-how many ways do we have?
2, change the way the date is displayed-the date and time of the display form
3. Convert the current date to a Unix timestamp value
4. Change the date
A. Adding time
B. Subtract 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 expressed as the number of seconds elapsed since 0 o'clock January 1, 1970, which is known as the Unix timestamp (Unix Epoch).
If we have the code for this segment:
?
echo Time ();
?
will return a value of 958905820
And this time is May 21, 2000 12:43.
You might say this is pretty good. When it doesn't help me, or only a little help. In PHP, a date-processed function must use the timestamp value returned by Time (). Also, because PHP uses the same timestamp values in both UNIX and Windows systems, this allows you to migrate between different systems without having to modify the code. Another benefit is that the time () function returns an integer that you can save as an integer or text field in the database without having to use a special date/Time field.
Now that you have a basic understanding of Unix timestamp values, let's show you how it's actually used.

Change the way date is displayed-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 timestamp value for UNIX.
The formatted string displays the date and time of the format you want to see by some simple special formatting characters. Suppose you want the date to display "18h01 Sunday" 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 in the date and Time function library. There are a number of special formatting characters that they represent, such as the day of the week, the English name of the month, the year in 2 or 4 digits, whether it is morning (AM) or PM (PM), and so on. The special characters we need for this example are:
' H '-hour of 24 hours
' I '-minute
' L '-the English full name of the day of the week
' d '-the first day of the month
' F '-the full English name of the month
So our formatted 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 result we get is:
180609 Sunday
The result looks a little strange. Let's check the PHP manual again, the original ' H ' represents the 12-hour hour. This proves again the truth: "The computer does what you tell it to do, not what you want it to do." We have two options. The first is to use the escape character "" in front of H:
echo Date ("Hhi l D F", Time ());
We get the result:
18h12 Sunday
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 an escape character for each character?
The answer, of course, is no. We use another function, strftime ().
There are two benefits of strftime (). The first benefit is not within the scope of this article-if you use the setlocale () function, you can get the name of the month by Strftime for the corresponding language. Another benefit is that you can include special date and time formatting characters in your string. It also means that regardless of whether you want to learn all the special formatting characters of the date () function, you must learn a whole set of completely different formatting characters.
Strftime () does not work the same way as date (), except that a percent semicolon must be added before the special formatting character. If you use the Strftime () function, the code for the preceding example is as follows:
?
Echo strftime ("%hh%m%A%d%b", Time ());
?
The result is:
18h24 Sunday
This may seem to simplify the complex, but consider if you need to display "Today is Sunday 2000." The time is somewhere close to 18h24. "I think using the date () function is no doubt annoying.
At the beginning, I mentioned that we had two ways to get useful data from the UNIX timestamp values. We just learned about date () and strftime (). Another getdate (). This function requires only the timestamp value of UNIX as a parameter, 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 returned result is:
Sunday
In addition to "weekday", the other parts of the array are:
"Seconds" – seconds
"Minutes" – min
"Hours" – hours
"Mday"-the day of the month
"Wday"-the day ordinal of the week (number)
"Mon"-month (number)
"Year" – Years
"Yday"-R the day of the Year (number)
"Month"-month full name
We can now get an easy-to-identify date and time. What about the rest?

* * Convert the current date to a Unix timestamp value

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 Unix timestamp value.
The format of the function is: int mktime (int hour, int minute, int second, int month, int day, int year, 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 these parameters must be filled in. Setting to 0 means that the time is midnight.
?
$access _date = "2000/05/27";
The explode () function uses a string as a boundary to break down another string. This example $access_date through the string "/" to decompose
$date _elements = Explode ("/", $access _date);
At this time
$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 more complicated case 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]);
?

* * Date Modified

Sometimes we need to know what time it is after 6 hours, the date 35 days ago, or how many seconds have elapsed since you last played Quake3. We already know how to get the timestamp value of Unix from a separate date and time using the Mktime () function. What should we do if we need a Unix timestamp value that is not the current date and time? Here are some exercises that can help explain what we have to do later.
As you can see earlier, Mktime () uses the following parameters: hours, minutes, seconds, months, days, and years. Think of the second section, the GETDATE () function can get these parameters for us.
?
Put the current timestamp value in an array
$timestamp = time ();
Echo $timestamp;
echo "P";
$date _time_array = getdate ($timestamp);
Re-generation of Unix timestamp values 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 something confusing. I'll use some variables to make the above program look easier to understand.
?
Put the current timestamp value in 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-generation of Unix timestamp values with the Mktime () function
$timestamp = Mktime ($hours, $minutes, $seconds, $month, $day, $year);
Echo $timestamp;
?
Now we will put the timestamp value produced 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 turn the time to the next day for us.
?
Put the current timestamp value in 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-generation of Unix timestamp values with the Mktime () function
Added 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
Reducing the time is the same-you just need to reduce the value of the corresponding variable.
The difference between getting two different time values is also very simple. All you need to do is convert the two time values to a UNIX timestamp value, and subtract from the two. The difference between the two is the number of seconds separated by two time. 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 because I can't find an ASP-like DateDiff function in PHP. After introducing how PHP handles the date and time, let's port the two commonly used functions in ASP to PHP. The first function is a dateadd.
According to VBScript's documentation, the DATEADD (interval,number,date) function is defined as "returns the date that the specified time interval was added. ”
Inetrval is a string expression that represents the interval to be added, such as minutes or days; number is a numeric expression that represents the number of time intervals to add;
The Interval (time interval string expression) can be any of the following values:
YYYY year
Q Quarter Quarter
M month
Y day of year number of years
D Day
W weekday days of the week
WW Week of Year Week
H Hour Hours
N Minute min
s second s
The functions of W, Y and D are exactly the same, that is, add one 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); 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", $temptime);
echo "P";
Echo strftime ("%hh%m%A%d%b", $temptime);
?
We will get:
15h41 Saturday June
16H31 Saturday June
Add the DateDiff function to PHP
Now that DateAdd is done, 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 a constant of Sunday or Monday and the first week of the year.) And we only allow intervals to have the following five values: "W" (week), "D" (Day), "H" (hours), "n" (minutes), and "s" (seconds).

Let's see how we can come up with: The following code is what we need:
?
Function DateDiff ($interval, $date 1, $date 2) {
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", $currenttime);
echo "Time plus minutes:". Strftime ("%hh%m%A%d%b", $newtime). " BR ";
$temptime = DateDiff ("n", $currenttime, $newtime);
echo "Interval between:" $temptime;
?
If all goes well, you can see the following results:
Current TIME:16H23 Saturday June
Time plus minutes:17h13 Saturday June
Interval between, 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, then unzip it to the root of the PHP4, recompile PHP, and compile with the--enable-bcmath option. (see PHP4 for details Readme.bcmath). The PHP4 version of Windows does not require any patching to directly use BC high-precision functions.
Now that you've got the function to handle the date and time, the rest is how to apply it to your PHP program.

http://www.bkjia.com/PHPjc/317664.html www.bkjia.com true http://www.bkjia.com/PHPjc/317664.html techarticle This article contains the following: 1. Get the current date and time-how many ways do we have? 2, change the way the date is displayed-date and time of display 3, convert the current date ...

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