PHP Date processing function _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:

1. A value of 958905820 will be returned, at which 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:

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

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

1. The result returned 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:

1. because I do not know the hours, minutes and seconds at the same time these parameters must be filled, I set it to 0. Setting to 0 means that the time is midnight.

1. We look at a more complex case than simply getting a date from an Access database, we get a date and time in the following format: 2000/05/27 02:40:21 PM

1.
* 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.

1.!--? 2.//puts the current timestamp value in an array of 3. $timetimestamp = time (); 4.echo $timestamp; 5.echo "P"; 6. $date _time_array = getdate ($timestamp); 7.//using the Mktime () function to regenerate the UNIX timestamp value 8. $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"]); 9.echo $timestamp; 10.? --> seems a bit confusing. I'll use some variables to make the above program look easier to understand.

1.!--? 2.//puts the current timestamp value in an array of 3. $timetimestamp = time (); 4.echo $timestamp; 5.echo "P"; 6. $date _time_array = getdate ($timestamp); 7. $hours = $date _time_array["Hours"]; 8. $minutes = $date _time_array["Minutes"]; 9. $seconds = $date _time_array["seconds"]; $month = $date _time_array["Mon"]; $day = $date _time_array["Mday"]; $year = $date _time_array["year"]; 13.//using the Mktime () function to re-create the Unix timestamp value. $timestamp = Mktime ($hours, $minutes, $seconds, $month, $day, $year); 15.echo $timestamp; 16.? --> now we will 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 turn the time to the next day for us.

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

1.!--? 2.function DateAdd ($interval, $number, $date) {3. $date _time_array = getdate ($date); 4. $hours = $date _time_array["Hours"]; 5. $minutes = $date _time_array["Minutes"]; 6. $seconds = $date _time_array["seconds"]; 7. $month = $date _time_array["Mon"]; 8. $day = $date _time_array["Mday"]; 9. $year = $date _time_array["year"]; 10.switch ($interval) {11.case "yyyy": $year + = $number; 12.case "Q": $month + = ($number); Break 13.case "M": $month + = $number; Break 14.case "y": 15.case "D": 16.case "W": $day + = $number; Break 17.case "ww": $day + = ($number *7); Break 18.case "H": $hours + = $number; Break 19.case "n": $minutes + = $number; Break 20.case "s": $seconds + = $number; Break $timestamp = Mktime ($hours, $minutes, $seconds, $month, $day, $year); 23.return $timestamp;} 24.? --> We can save the above code as a dateadd.inc file, and then run the following code:

1. we will receive:
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:

1.!--? 2.Function DateDiff ($interval, $date 1, $date 2) {3.//Gets the number of seconds between two dates 4. $timedifference = $date 2-$date 1; 5.switch ($interval) {6.case "W": $retval = Bcdiv ($timedifference, 604800); break; 7.case "D": $retval = Bcdiv ($timedifference, 86400); Break 8.case "h": $retval = Bcdiv ($timedifference, 3600); Break 9.case "n": $retval = Bcdiv ($timedifference, 60); Break 10.case "s": $retval = $timedifference; Break One.} 12.return $retval;} 13.? --> Save the above code as a datediff.inc file, and then run the following code:

1. 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 and unzip it to the root of PHP4, recompile PHP, and compile with--enable-bcmath options. (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/371382.html www.bkjia.com true http://www.bkjia.com/PHPjc/371382.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 the Display Form 3, the conversion of the present 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: 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.