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

2019-04-10 05:34:02王冬梅

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'); 
?> 

易采站长站小编补充:真正的干货在这里了

<?php 
header('Content-Type: text/html; charset=utf-8'); 
 
//PHP时间戳函数获取指定日期的unix时间戳 
echo strtotime('2018-1-19').PHP_EOL; 
echo time().PHP_EOL; 
 
//PHP时间戳函数获取英文文本日期时间 
echo date('Y-m-d H:i:s', 1516291200).PHP_EOL; 
echo date('Y-m-d H:i:s', time()).PHP_EOL; 
 
//打印明天此时的时间戳 
echo date('Y-m-d H:i:s',strtotime('+1 day')).PHP_EOL; 
 
//打印昨天此时的时间戳 
echo date('Y-m-d H:i:s',strtotime('-1 day')).PHP_EOL; 
 
//打印下个星期此时的时间戳 
echo date('Y-m-d H:i:s',strtotime('+1 week')).PHP_EOL; 
 
//打印上个星期此时的时间戳 
echo date('Y-m-d H:i:s',strtotime('-1 week')).PHP_EOL; 
 
//打印指定下星期几的时间戳 
echo date('Y-m-d H:i:s',strtotime('next Thursday')).PHP_EOL; 
 
//打印指定上星期几的时间戳 
echo date('Y-m-d H:i:s',strtotime('last Thursday')).PHP_EOL; 
 
//时间戳获取年月日时分秒 
$datetimeArr = getdate(1516329995); 
$hours = $datetimeArr["hours"]; 
$minutes = $datetimeArr["minutes"]; 
$seconds = $datetimeArr["seconds"]; 
$month = $datetimeArr["mon"]; 
$day = $datetimeArr["mday"]; 
$year = $datetimeArr["year"]; 
echo "year:$yearnmonth:$monthnday:$daynhour:$hoursnminutes:$minutesnseconds:$secondsn"; 
 
//日期时间截取年月日 
$datetime = date('Y-m-d H:i:s', 151641111119); 
echo ((int)substr($datetime,0,4)).PHP_EOL;;//获取年份 
echo ((int)substr($datetime,5,2)).PHP_EOL;;//获取月份 
echo ((int)substr($datetime,8,2)).PHP_EOL;;//获取日份 								 
			 
相关文章 大家在看