This article contains the following content:
1. Get the current date and time - how many ways do we have?
2. Change the way date is displayed - the display format of date and time
3. Convert the current date to Unix timestamp value
4. Change the date
a. Add time
b . Subtract time
c. Find the interval between two dates
5. Add DateAdd function for PHP
6. Add DateDiff function for PHP
**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. This is called a UNIX timestamp (Unix Epoch).
If we have such a piece of code:
? echo time(); ?
will return the value 958905820
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.
You have basically understood the Unix timestamp value, now let us show its practical use.
Change the way date is displayed - the display format of date and time
PHP provides two methods to convert Unix timestamp values 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.
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 in 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
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 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. An additional 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 a percent sign % must be added in front of the special formatting character. If you use the strftime() function, the code of the previous example is as follows:
? echo strftime ("%Hh%M %A %d %b" ,time()); ?
结果为:
18h24 Sunday 21 May
这也许看起来将简化繁,但考虑一下如果你所需要的显示的为"Today is Sunday 21 May 2000. The time is somewhere close to 18h24." 我想使用date()函数无疑令人感到厌烦。
在开始的时候,我提及我们有两种方式可以从Unix时间戳值中得到有用的数据。我们刚刚了解了date()和strftime()。另一个getdate()。这个函数只需要Unix 的时间戳值作为参数,而函数的返回值为日期和时间的数组。
下面是一个例子:
? $date_time_array = getdate (time()); echo $date_time_array[ "weekday"]; ?
返回的结果为:
Sunday
除了"weekday",该数组的其他部分为:
"seconds" –秒
"minutes" –分
"hours" –小时
“mday" - 本月的第几天
"wday" -本周的第几天(数字)
"mon" -月(数字)
"year" –年
"yday" - r本年的第几天(数字)
"month" -月份全名
我们现在可以得到容易辨认的日期和时间。那么其他呢?
**转换现在的日期为Unix的时间戳值
通常你必须处理一些日期或时间格式的数据。打开M$的一个Access数据库,所有的日期都以YYYY/MM/DD的格式存储,加入目前的日前即为2000/05/27。Mktime()函数可以将一个时间转换成Unix的时间戳值。
函数的格式为:int mktime(int hour, int minute, int second, int month, int day, int year, int [is_dst] );
从左往右你必须提供小时、分、秒、月、天和年。最后一个参数用于指定你是否处于夏令时,此参数是可选的,所以我们将忽略它。
代码如下:
? echo mktime (0, 0,0 ,5, 27,2000 ); ?
由于不知道小时、分和秒同时这些参数必须填写,我将其设置为0。设置为0意味着时间为午夜。
? $access_date = "2000/05/27"; //explode()函数用一个字符串作为分界来分解另一个字符串。这个例子$access_date通过字符串”/”来分解 $date_elements = explode("/" ,$access_date); // 此时 // $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]); ?
我们看一个比从Access数据库单纯获得日期更复杂的情况,我们得到一个以下格式的日期和时间:2000/05/27 02:40:21 PM
? // 来自Access的字符串 $date_time_string = "2000/05/27 02:40:21 PM"; // 将字符串分解成3部分-日期、时间和上午/下午 $dt_elements = explode(" " ,$date_time_string); // 分解日期 $date_elements = explode("/" ,$dt_elements[ 0]); // 分解时间 $time_elements = explode(":" ,$dt_elements[ 1]); // 如果是下午,我们将时间增加12小时以便得到24小时制的时间 if ($dt_elements [2]== "PM") { $time_elements[ 0]+=12;} // 输出结果 echo mktime ($time_elements [0], $time_elements[ 1], $time_elements[ 2], $date_elements[1], $date_elements[2], $date_elements[0]); ?
**修改日期
有时我们需要知道6小时以后是什么时间,35天前的日期或者从你最后一次玩Quake3后已过去多少秒。我们已经知道如何用mktime()函数从单独的日期和时间中获得Unix的时间戳值。如果我们需要的并非目前日期和时间的Unix时间戳值,我们该咋办?下面是一些练习可以帮助说明我们后面所要做的。
正如前面所见,mktime()使用以下参数:小时、分、秒、月、天和年。想想第二节,getdate()函数可以为我们获得这些参数。
? // 将目前的时间戳值放入一数组内 $timestamp = time(); echo $timestamp; echo "p"; $date_time_array = getdate( $timestamp); // 用mktime()函数重新产生Unix时间戳值 $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; ?
看起来有一些令人感到迷惑。我将用一些变量来使上面的程序看起来更容易了解。
? // 将目前的时间戳值放入一数组内 $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"]; // 用mktime()函数重新产生Unix时间戳值 $timestamp = mktime($hours ,$minutes, $seconds,$month ,$day,$year); echo $timestamp; ?
现在我们将由getdate()所产生的时间戳值放入相对应的名称变量中,所以代码变得相对容易阅读和理解。现在如果我们需要在目前的时间上加上19个小时,我们用$hours+19代替mktime()函数中的$hours。mktime()将自动为我们将时间转到第二天。
? // 将目前的时间戳值放入一数组内 $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"]; // 用mktime()函数重新产生Unix时间戳值 // 增加19小时 $timestamp = mktime($hours + 19, $minutes,$seconds ,$month, $day,$year); echo strftime( "%Hh%M %A %d %b",$timestamp); echo "br~E after adding 19 hours"; ?
运行后得到:
14h58 Saturday 03 Jun
09h58 Sunday 04 Jun
~E after adding 19 hours
减少时间也是同样的-你只需要减少相应变量的值即可。
得到两个不同时间值的差同样也是非常简单。你所需要做的只是将两个时间值转换为Unix的时间戳值,然后两者相减即可。两者之差即为两个时间所相隔的秒数。另外一些算法可以很快地将秒转为天、小时、分和秒。
**为PHP添加DateAdd函数
正如在文章一开始我所说的-写本文的原因是因为我在PHP中找不到类似ASP的DateDiff函数。在介绍完PHP是如何处理日期和时间,让我们将ASP中常用的两个函数移植到PHP。第一个函数是DateAdd。
根据Vbscript的文档,DateAdd(interval,number,date)函数的定义为“返回已添加指定时间间隔的日期。”
Inetrval为表示要添加的时间间隔字符串表达式,例如分或天;number为表示要添加的时间间隔的个数的数值表达式;Date表示日期。
Interval(时间间隔字符串表达式)可以是以下任意值:
yyyy year年
q Quarter季度
m Month月
y Day of year一年的数
d Day天
w Weekday一周的天数
ww Week of year周
h Hour小时
n Minute分
s Second秒
w、y和d的作用是完全一样的,即在目前的日期上加一天,q加3个月,ww加7天。
? 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;} ? 我们可以将上面的代码保存为dateadd.inc文件,然后运行以下代码: ? 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); ?
我们将得到:
15h41 Saturday 03 Jun
16h31 Saturday 03 Jun
为PHP添加DateDiff函数
现在DateAdd已经完成,那么DateDiff呢?
根据文档,DateDiff(interval,date1,date2)函数的定义为“返回两个日期之间的时间间隔”。
Intervals参数的用法与DateAdd函数中的相同。出于避免过于复杂的考虑,我们决定忽略Vbscript中DateDiff函数中其它复杂的参数,即其两个可选的参数变量[firstdayofweek[, firstweekofyear]](它们用于决定星期中第一天是星期天还是星期一和一年中第一周的常数。而且我们只允许intervals有以下五个值:"w"(周)、"d"(天)、"h"(小时)、"n"(分钟) 和"s"(秒)。
Let's see what we can come up with: 下面的代码是我们所需要的:
? Function DateDiff ($interval, $date1,$date2) { // 得到两日期之间间隔的秒数 $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;} ?
将上面的代码存为datediff.inc文件,然后运行下面的代码:
? 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; ?
如果一切顺利,你可以看到以下结果:
Current time: 16h23 Saturday 03 Jun
Time plus 50 minutes: 17h13 Saturday 03 Jun
Interval between two times: 50
如果你在Unix机器上运行PHP,你必须编译PHP支持BC高精度函数。你必须从以下地址http://www.php.net/extra/number4.tar.gz下载BC库,然后将其解压到PHP4的根目录下,重新编译PHP,编译时要加上--enable-bcmath的选项。(详细说明见PHP4中README.BCMATH)。PHP4的Windows版本则不需要做任何修补即可直接使用BC高精度函数。
现在你已经得到处理日期和时间的函数,剩下的就是如何将其运用到你的PHP程序中
The above is the detailed content of What are the methods of date processing in PHP. For more information, please follow other related articles on the PHP Chinese website!