PHP date processing function integer date format

  • 2020-03-31 21:27:19
  • OfStack

When I used to work with ASP, it was fairly simple to solve this problem. ASP has a function called DateDiff that gives you the number of months, days, and seconds between two days. When I searched the PHP manual, I found that PHP does not have similar functions.
This article contains the following contents:
1. Get the current date and time - how many ways do we have?
2. Change the way the date is displayed -- the way the date and time are displayed
3. Convert the current date to the Unix timestamp value
Change the date
A. add time
B. Minus time
C. find the space between the two dates
5. Add the DateAdd function to PHP
Add the DateDiff function to PHP
** get the current date and time
In Unix, time is represented by counting the number of seconds that have passed since zero on January 1, 1970. This is called the Unix timestamp (Unix Epoch).
If we have a piece of code that looks like this:
 
<? 
echo time(); 
?>; 

Returns a value of 958905820
The time was 12:43 on May 21, 2000.
You might say that's pretty good. When it doesn't help me, or only helps me a little. In PHP, any function that handles a date must use the timestamp value returned by time(). Also, since PHP USES the same timestamp values on both Unix and Windows systems, this allows you to port between systems without changing the code. Another benefit is that the time() function returns an integer, which you can store in the database as an integer field or as a text field instead of using a special date/time field.
Now that you have a basic understanding of Unix's timestamp values, let's show you what it actually does.
Change the way the date is displayed - the way the date and time are displayed
PHP provides two ways to convert Unix timestamp values into useful data. The first is the date() function. This function takes two arguments - the first string for the format you want to return, and the second for the Unix timestamp value.
The format string USES some simple special formatting characters to display the date and time of the format you want to see. Suppose you want the date to be "18h01 Sunday 21 May" in this format.
We need to use a special formatting 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 formatting characters that represent English names similar to the day of the week, the month, the year with two or four digits, AM or PM, and others. The special characters we need for this example are:
'H' - 24-hour hours
'I' - minutes
'l'- the full English name of the day of the week
'd'- the date of the month
'F'- the full English name of the month
Therefore, 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 result we get is:
Sunday May 21 180609
The results seem odd. Let's take a look at the PHP manual again. The original 'h' stood for a 12-hour hour. This proves once again the truth that "computers do what you tell them to do, not what you want them 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:
18 h12 Sunday May 21
This is just 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, of course, is 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 names of the months in the 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 will have to learn a whole set of different formatting characters.
Strftime () works no differently than date(), except that a percent sign % must be added before a special formatting character. If you use the strftime() function, the code for the previous example is as follows:
 
<? 
echo strftime ("%Hh%M %A %d %b" ,time()); 
?>; 

The result is:
18 h24 Sunday May 21
This may seem like it will simplify things, but consider if you need to display as
"Today is Sunday 21 May 2000. The time is somewhere close to 18h24."
I think the date() function is definitely annoying.
At the beginning, I mentioned that there are two ways to get useful data from Unix timestamp values. We just learned about date() and strftime(). Another getdate(). This function takes only the Unix timestamp value as an argument, and the return value of the function is an array of dates and times.
Here's an example:
 
<? 
$date_time_array = getdate (time()); 
echo $date_time_array[ "weekday"]; 
?>; 

The result returned is:
Sunday
In addition to "weekday", the rest of the array is:
"Seconds" � s
"Minutes" � points
"Hours" � hours
"Mday" - the day of the month
"Wday" - day of the week (number)
"Mon" - month (number)
"Year" � years
"Yday" - r day of the year (number)
"Month" - the full name of the month
We now have easily identifiable dates and times. What else?
** converts the current date to the Unix timestamp value
Usually you have to deal with some data in date or time format. Open an Access database of M$, and all dates are stored in YYYY/MM/DD format, adding the current day to 2000/05/27. The Mktime() function converts a time to a Unix timestamp value.
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, 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 ); 
?>; 

Since I didn't know that the hours, minutes, and seconds had to be filled in at the same time, I set them to 0. Setting it to 0 means midnight.
 
<? 
$access_date = "2000/05/27"; 
//The limit () function USES one string as a boundary to decompose another. This example $access_date is broken down 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]); 
?>; 

Looking 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
 
<? 
//A string from Access
$date_time_string = "2000/05/27 02:40:21 PM"; 
//Split the string into three parts-date, time, and am/PM
$dt_elements = explode(" " ,$date_time_string); 
//Date of decomposition
$date_elements = explode("/" ,$dt_elements[ 0]); 
//Break time
$time_elements = explode(":" ,$dt_elements[ 1]); 
//If it's in the afternoon, we'll add 12 hours to get a 24-hour schedule
if ($dt_elements [2]== "PM") { $time_elements[ 0]+=12;} 
//The output
echo mktime ($time_elements [0], $time_elements[ 1], $time_elements[ 2], $date_elements[1], $date_elements[2], $date_elements[0]); 
?>; 

** modify date
Sometimes we need to know what time is 6 hours later, the date 35 days ago or how many seconds have passed since you last played Quake3. We've learned how to use the mktime() function to get Unix timestamp values from separate dates and times. What if we don't need Unix timestamp values for the current date and time? Here are some exercises to help illustrate what we'll do later.
As seen earlier, mktime() USES the following parameters: hours, minutes, seconds, months, and years. Consider the second section, where the getdate() function gets these parameters for us.
 
<? 
//Puts the current timestamp value into an array
$timestamp = time(); 
echo $timestamp; 
echo "p"; 
$date_time_array = getdate( $timestamp); 
//Regenerate 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; 
?>; 

It looks a little confusing. I'll use some variables to make the above program easier to understand.
 
<? 
//Puts the current timestamp value into 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"]; 
//Regenerate 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 is relatively easy to read and understand. Now if we need to add 19 hours to our current time, we replace the $hours in the mktime() function with $hours+19. Mktime () will automatically move the time to the next day for us.
 
<? 
//Puts the current timestamp value into 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"]; 
//Regenerate the Unix timestamp value with the mktime() function
//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 operation:
14 h58 Saturday 03 Jun
09 h58 Sunday 4 Jun
~E after adding 19 hours
The same goes for reducing time - you just reduce the value of the corresponding variable.
It's also very easy to get the difference between two different values of time. All you need to do is convert the two time values to Unix timestamp values and subtract them. The difference between the two is the number of seconds between the two times. Other algorithms quickly convert seconds into days, hours, minutes, and seconds.
** add the DateAdd function to PHP
As I said at the beginning of this article - the reason I wrote this article is because I couldn't find a DateDiff function like ASP in PHP. After explaining how PHP handles dates and times, let's port two functions commonly used in ASP to PHP. The first function is DateAdd.
According to the Vbscript documentation, the DateAdd (interval, number, date) function is defined as "returning the date that the specified interval has been added."
Inetrval is a string expression for the interval to be added, such as minutes or days; Number is a numeric expression representing the number of time intervals to be added; Date represents a Date.
Interval can be any of the following values:
Yyyy year year
Q Quarter Quarter
M the Month Month
The number of days of the year
D Day Day
The days of the week
Ww Week of year
H Hour Hour
N Minute points
S Second seconds
The functions of w, y and d are exactly the same, that is, add one day to the current date, q plus 3 months, and 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" ,50,$temptime); 
echo "p"; 
echo strftime( "%Hh%M %A %d %b",$temptime); 
?>; 

We will get:
15 h41 Saturday 03 Jun
16 h31 Saturday 03 Jun
Add the DateDiff function to PHP
Now that DateAdd is complete, what about DateDiff?
According to the documentation, the DateDiff(interval,date1,date2) function is defined as "returning the interval between two dates."
The usage of the Intervals parameter is the same as in the DateAdd function. To avoid getting too complicated, we decided to ignore the other complex parameters of the DateDiff function in Vbscript, namely its two optional parameter variables [firstdayofweek[, firstweekofyear]], which are used to determine whether the firstdayof the week is Sunday or Monday and the constants for the firstweekof the year. And we allow only these five intervals: "w"(week), "d" (day), "h" (hour), "n" (minute), and "s" (second).
Let's see what we can come up with:
 
<? 
Function DateDiff ($interval, $date1,$date2) { 
//Gets the number of seconds between the 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, 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",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 all 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 precision functions. You must download BC libraries from the following address http://www.php.net/extra/number4.tar.gz, then PHP4 unpacking it to the root directory, recompile PHP, compile time plus - enable - bcmath options. See readme.bcmath in PHP4 for details. The Windows version of PHP4 USES the BC precision function without any tinkering.
Now that you have the function that handles the date and time, all that remains is how to apply it to your PHP program.

Related articles: