欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP日期时间函数的高级应用技巧

程序员文章站 2023-11-09 21:23:40
checkdate($month,$date,$year)如果应用的值构成一个有效日期,则该函数返回为真。例如,对于错误日期2005年2月31日,此函数返回为假。在日期用于...
checkdate($month,$date,$year)

如果应用的值构成一个有效日期,则该函数返回为真。例如,对于错误日期2005年2月31日,此函数返回为假。

在日期用于计算或保存在数据库中之前,可用此函数检查日期并使日期生效。

<?php
// returns false
echo checkdate(2,30,2005) ? "valid" : "invalid";
// returns true
echo checkdate(4,6,2010) ? "valid" : "invalid";
?>

getdate($ts)

在没有自变量的情况下,该函数以结合数组的方式返回当前日期与时间。数组中的每个元素代表日期/时间值中的一个特定组成部分。可向函数提交可选的时间标签自变量,以获得与时间标签对应的日期/时间值。

应用此函数来获得一系列离散的,容易分离的日期/时间值。


<?php
// get date as associative array
$arr = getdate();
echo "date is " . $arr['mday'] . " " . $arr['weekday'] . " " . $arr['year'];
echo "time is " . $arr['hours'] . ":" . $arr['minutes'];
?>

mktime($hour, $minute, $second, $month, $day, $year)

此函数的作用与getdate()的作用相反:它由一系列的日期与时间值生成一个unix时间标签(gmt时间1970年1月1日到现在消逝的秒数)。不用自变量时,它生成当前时间的unix时间标签。

用此函数获得即时时间的unix时间标签。这种时间标签通常用于许多数据库与程序语言中。


<?php
// returns timestamp for 13:15:23 7-jun-2006
echo mktime(13,15,23,6,7,2006);
?>

date($format, $ts)

此函数将unix时间标签格式化成一个可人为阅读的日期字符串。它是php日期/时间api中功能最为强大的函数,可用在一系列的修正值中,将整数时间标签转变为所需的字符串格式。

为显示格式化时间或日期时,应用此函数。


<?php
// format current date
// returns "13-sep-2005 01:16 pm"
echo date("d-m-y h:i a", mktime());
?>

strtotime($str)

此函数将可人为阅读的英文日期/时间字符串转换成unix时间标签。

应用此函数将非标准化的日期/时间字符串转换成标准、兼容的unix时间标签。


<?php
// returns 13-sep-05
echo date("d-m-y", strtotime("today"));
// returns 14-sep-05
echo date("d-m-y", strtotime("tomorrow"));
// returns 16-sep-05
echo date("d-m-y", strtotime("today +3 days"));
?>

strftime($format,$ts)

如前面的setlocale()函数定义的那样,此函数将unix时间标签格式化成适用于当前环境的日期字符串。

应用此函数建立与当前环境兼容的日期字符串。


<?php
// set locale to france (on windows)
setlocale(lc_time, "fra_fra");

// format month/day names
// as per locale setting
// returns "septembre" and "mardi"

echo strftime("month: %b ");
echo strftime("day: %a ");
?>

microtime()

如前面的setlocale()函数定义的那样,此函数将unix时间标签格式化成适用于当前环境的日期字符串。

应用此函数建立与当前环境兼容的日期字符串。


<?php
// get starting value
$start = microtime();

// run some code
for ($x=0; $x<1000; $x++) {
$null = $x * $x;
}

// get ending value
$end = microtime();

// calculate time taken for code execution
echo "elapsed time: " . ($end - $start) ." sec";
?>

gmmktime($hour, $minute, $second, $month, $day, $year)

此函数由一系列用gmt时间表示的日期与时间值生成一个unix时间标签。不用自变量时,它生成一个当前gmt即时时间的unix时间标签。

用此函数来获得gmt即时时间的unix时间标签。


<?php
// returns timestamp for 12:25:23 9-jul-2006
echo gmmktime(12,25,23,7,9,2006);
?>

gmdate($format, $ts)

此函数将unix时间标签格式化成可人为阅读的日期字符串。此日期字符串以gmt(非当地时间)表示。

用gmt表示时间标签时应用此函数。


<?php
// format current date into gmt
// returns "13-sep-2005 08:32 am"
echo gmdate("d-m-y h:i a", mktime());
?>

date_default_timezone_set($tz)、date_default_timezone_get()

此函数此后所有的日期/时间函数调用设定并恢复默认的时区。

注:此函数仅在php 5.1+中有效。

此函数是一个方便的捷径,可为以后的时间操作设定时区。


<?php
// set timezone to utc
date_default_timezone_set('utc');
?>