频道栏目
首页 > 资讯 > 日期 > 正文

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

16-01-06        来源:[db:作者]  
收藏   我要投稿

具体讲解PHP的日期时间函数date()中先容了PHP日期时间函数的简略用法,这类将先容更多的函数来丰富我们的利用。

checkdate($month,$date,$year)

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

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

// returns false
echo checkdate(2,30,2005) ? 'valid' : 'invalid';
// returns true
echo checkdate(4,6,2010) ? 'valid' : 'invalid';
?>
getdate($ts)

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

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

// 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时间标签。这种时间标签通常用于很多数据库与程序语言中。

// returns timestamp for 13:15:23 7-Jun-2006
echo mktime(13,15,23,6,7,2006);
?>
date($format, $ts)

此函数将UNIX时间标签格局化成一个可人为浏览的日期字符串。它是PHP日期/时间API中功效最为强盛的函数,可用在一系列的修正值中,将整数时间标签转变为所需的字符串格局。

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

// format current date
// returns '13-Sep-2005 01:16 PM'
echo date('d-M-Y h:i A', mktime());
?>
strtotime($str)

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

利用此函数将非尺度化的日期/时间字符串转换成尺度、兼容的UNIX时间标签。

// 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时间标签格局化成实用于当前环境的日期字符串。

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

// 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时间标签格局化成实用于当前环境的日期字符串。

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

// 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时间标签。

// returns timestamp for 12:25:23 9-Jul-2006
echo gmmktime(12,25,23,7,9,2006);
?>
gmdate($format, $ts)

此函数将UNIX时间标签格局化成可人为浏览的日期字符串。此日期字符串以GMT(非当地时间)表现。

用GMT表现时间标签时利用此函数。

// 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 中有效。

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

// set timezone to UTC
date_default_timezone_set('UTC');
?>

相关TAG标签
上一篇:应用PHP的日期与时间函数提高开发技巧
下一篇:php日期转时间戳,指定日期转换成时间戳
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站