Home  >  Article  >  Backend Development  >  PHP date processing function integer date format_PHP tutorial

PHP date processing function integer date format_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:32:13905browse

Solving this problem was quite simple when I used ASP in the past. ASP has a corresponding function DateDiff that can give the number of months, days and seconds between two dates. When I searched the PHP manual I found that PHP does not have a similar function.
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 display format of date and time
3. Convert the current date to the Unix timestamp value
4. Change the date
a. Add time
b . Subtract time
c. Find the interval between two dates
5. Add DateAdd function to PHP
6. Add DateDiff function to PHP
** to get the current date and time
In Unix, time is expressed by calculating the number of seconds that have passed since 0:00 on January 1, 1970, which is called a UNIX timestamp (Unix Epoch).
If we have a piece of code like this:

Copy code The code is as follows:

echo time();
?>;

will return the value 958905820
and the time at this time is 12:43 on May 21, 2000.
You might say this is pretty good. When this doesn't help me at all, or only a little. In PHP, all date processing functions must use the timestamp value returned by time(). At the same time, since PHP uses the same timestamp value in both Unix and Windows systems, this allows you to port it between different systems without modifying the code. Another benefit is that the time() function returns an integer, which you can store in the database as an integer field or a text field without having to use a special date/time field.
Now that you have a basic understanding of Unix timestamp values, let’s show you what they are used for.
Change the way date is displayed - the display format of date and time
PHP provides two methods to convert Unix timestamp value into useful data. The first is the date() function. This function takes two parameters - the first string is used to set the format you wish to return, and the second is the Unix timestamp value.
The format string uses some simple special formatting characters to display the date and time in the format you want to see. Suppose you want the date to be displayed in the format "18h01 Sunday 21 May".
We need to use a special formatting character for each part of the string, which you can find from the date and time function library in the PHP manual. There are a lot of such special formatting characters. They represent the day of the week, the English name of the month, the year represented by 2 or 4 digits, whether it is morning (AM) or afternoon (PM) and others. The special characters we need for this example are:
'H' - the hour in the 24-hour clock
'i' - the minute
'l' - the full English name of the day of the week
'd' - The day of this month
'F' - the full English name of the month
Therefore, our format string is "Hhi l d F", and the PHP code is:
Copy code The code is as follows:

echo date ("Hhi l d F" ,time());
?>;

When we execute this code, we find that the result we get is:
180609 Sunday 21 May
This result looks a bit strange. Let's check the PHP manual again. It turns out that 'h' represents the hour in the 12-hour clock. This once again proves the truth: "The computer only does what you tell it to do, not what you want it to do." We have two options. The first one is to use the escape character "" before h:
echo date ("Hhi l d F", time());
We get this result:
18h12 Sunday 21 May
This is exactly what we want. But if we need to include a date and time in a very complex sentence, do we need to use escape characters for each character?
The answer is of course no. We use another function strftime().
strftime() has two benefits.
The first benefit is beyond the scope of this article - if you use the setlocale() function, you can get the name of the month in the corresponding language through strftime.
Another benefit is that you can include special date and time formatting characters in your strings. This also means that whether or not you want to learn all the special formatting characters for the date() function, you have to learn a whole different set of formatting characters.
strftime() works no differently than date(), except that the special formatting character must be preceded by a percent sign %. If the strftime() function is used, the code of the previous example is as follows:
Copy the code The code is as follows:

echo strftime ("%Hh%M %A %d %b" ,time());
?>;

The result is:
18h24 Sunday 21 May
This may seem oversimplified, but consider what you need to display is
"Today is Sunday 21 May 2000. The time is somewhere close to 18h24."
I guess using the date() function is definitely annoying.
At the beginning, I mentioned that we have two ways to get useful data from Unix timestamp values. We just learned about date() and strftime(). Another getdate(). This function only requires a Unix timestamp value as a parameter, and the return value of the function is an array of date and time.
The following is an example:
Copy the code The code is as follows:

$date_time_array = getdate (time());
echo $date_time_array[ "weekday"];
?>;

The returned result is:
Sunday
except "weekday" , the other parts of the array are:
"seconds" - seconds
"minutes" - minutes
"hours" - hours
"mday" - the day of the month
"wday " -The day of the week (number)
"mon" -Month (number)
"year" -Year
"yday" - rThe day of the year (number)
"month" - the full name of the month
We can now get an easily identifiable date and time. What about others?
**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 of M$. All dates are stored in the format of YYYY/MM/DD. Adding the current date is 2000/05/27. The Mktime() function can convert a time into 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] );
You must provide hours, minutes, and seconds from left to right , month, day and year. 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:
Copy code The code is as follows:

echo mktime (0, 0 ,0 ,5, 27,2000 );
?>;

Since I don’t know the hours, minutes and seconds at the same time these parameters must be filled in, I set it to 0. Setting to 0 means the time is midnight.
Copy code The code is as follows:

$access_date = "2000/05/27";
//explode() function uses one string as a delimiter to explode another string. In this example $access_date is decomposed by the string "/"
$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] ; 40:21 PM


Copy code
The code is as follows: // String from Access
$date_time_string = "2000/05/27 02:40:21 PM";
// Decompose the string into 3 parts - date, time and AM/PM
$dt_elements = explode(" ", $date_time_string);
// Decomposition date
$date_elements = explode("/" ,$dt_elements[ 0]);
// Decomposition time
$time_elements = explode(":" ,$ dt_elements[ 1]);
// If it is afternoon, we add 12 hours to the time to get the 24-hour time
if ($dt_elements [2]== "PM") { $time_elements[ 0] +=12;}
//Output result
echo mktime ($time_elements [0], $time_elements[ 1], $time_elements[ 2], $date_elements[1], $date_elements[2], $date_elements [0]);
?>;


**Modification Date
Sometimes we need to know when it is 6 hours later, a date 35 days ago or since the last time you played How many seconds have passed since Quake3. We already know how to get a Unix timestamp value from a separate date and time using the mktime() function. What should we do if we need a Unix timestamp value other than the current date and time? Here are some exercises to help illustrate what we will do next.
As seen earlier, mktime() takes the following parameters: hours, minutes, seconds, months, days, and years. Think about Section 2, the getdate() function can get these parameters for us.



Copy code
The code is as follows:

// Put the current timestamp value into an array
$timestamp = time();
echo $timestamp;
echo "p";
$date_time_array = getdate( $timestamp);
// Use the mktime() function to regenerate the Unix timestamp value
$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;
?>;

Looks a little confusing. I'm going to use some variables to make the program above look easier to understand.
Copy code The code is as follows:

// Put the current timestamp value into an array Within
$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"];
// Use the mktime() function to regenerate the Unix timestamp value
$timestamp = mktime($hours,$ minutes, $seconds,$month ,$day,$year);
echo $timestamp;
?>;

Now we will get the timestamp value generated by getdate() into corresponding named variables, 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 $hours in the mktime() function. mktime() will automatically move the time to the next day for us.
Copy code The code is as follows:

// Put the current timestamp value into an array Within
$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"];
// Regenerate using mktime() function Unix timestamp value
// Add 19 hours
$timestamp = mktime($hours + 19, $minutes,$seconds ,$month, $day,$year);
echo strftime( "%Hh %M %A %d %b",$timestamp);
echo "br~E after adding 19 hours";
?>;

After running, you get:
14h58 Saturday 03 Jun
09h58 Sunday 04 Jun
~E after adding 19 hours
The same goes for reducing time - you just need to reduce the value of the corresponding variable.
Getting the difference between two different time values ​​is also very simple. All you need to do is convert the two time values ​​into Unix timestamp values ​​and then subtract the two. The difference between the two is the number of seconds between the two 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 because I can't find an ASP-like DateDiff function in PHP. After introducing how PHP handles dates and times, let us transplant two functions commonly used in ASP to PHP. The first function is DateAdd.
According to Vbscript's documentation, the DateAdd(interval,number,date) function is defined as "Returns the date to which the specified time interval has been added."
Inetrval is a string expression representing the time interval to be added, such as minutes or days; number is a numerical expression representing the number of time intervals to be added; Date represents the date.
Interval (time interval string expression) can be any of the following values:
yyyy year year
q Quarter quarter
m Month month
y Day of year
d Day
w Weekday Number of days in the week
ww Week of year week
h Hour hour
n Minute minute
s Second second
w, y and d have exactly the same effect , that is, add one day to the current date, add 3 months to q, and add 7 days to ww.
Copy code The code is as follows:

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 dateadd.inc file, and then run the following code:
Copy the code The code is as follows:

include('dateadd.inc');
$temptime = time();
echo strftime( "%Hh%M %A %d %b",$temptime) ;
$temptime = DateAdd("n" ,50,$temptime);
echo "p";
echo strftime( "%Hh%M %A %d %b",$temptime);
?>;

We will get:
15h41 Saturday 03 Jun
16h31 Saturday 03 Jun
Add DateDiff function for PHP
Now DateAdd is completed, What about DateDiff?
According to the documentation, the DateDiff(interval, date1, date2) function is defined as "returning the time interval between two dates".
The usage of the Intervals parameter is the same as in the DateAdd function. In order to avoid excessive complexity, we decided to ignore other complex parameters in the DateDiff function in Vbscript, namely its two optional parameter variables [firstdayofweek[, firstweekofyear]] (they are used to determine whether the first day of the week is Sunday or Constants for Monday and the first week of the year, and we only allow intervals to have the following five values: "w" (week), "d" (day), "h" (hour), "n" (minute). and "s" (seconds).
Let's see what we can come up with: The following code is what we need:
Copy code Code As follows:

Function DateDiff ($interval, $date1,$date2) {
// Get the number of seconds between two dates
$timedifference = $date2 - $date1;
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 datediff .inc file, and then run the following code:
Copy the code The code is as follows:

include( 'datediff.inc');
include('dateadd.inc');
$currenttime = time();
echo "Current time: ". strftime("%Hh%M %A %d %b" ,$currenttime)."br";
$newtime = DateAdd ("n",50 ,$currenttime);
echo "Time plus 50 minutes: ". strftime("%Hh%M % A %d %b" ,$newtime)."br";
$temptime = DateDiff ("n",$currenttime ,$newtime);
echo "Interval between two times: ".$temptime;
?>;

If everything goes well, you can see the following results:
Current time: 16h23 Saturday 03 Jun
Time plus 50 minutes: 17h13 Saturday 03 Jun
Interval between two times: 50
If you are running PHP on a Unix machine, you must compile PHP to support BC high-precision functions. You must download the BC library from the following address http://www.php.net/extra/number4.tar.gz, then unzip it to the root directory of PHP4, recompile PHP, and add --enable- when compiling. Options for bcmath. (See README.BCMATH in PHP4 for detailed instructions). The Windows version of PHP4 can directly use BC high-precision functions without any patching.
Now that you have the functions to handle dates and times, all that remains is how to apply them to your PHP program.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/322867.htmlTechArticleWhen I used ASP in the past, it was quite simple to solve this problem. ASP has a corresponding function DateDiff that can give two dates. The number of months, days and seconds between periods. After I searched the PHP manual I found...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn