PHP日期时间处理

2018-10-03 16:04:47
Reading:370
<?php
// 假定今天是:March 10th, 2001, 5:16:18 pm
$today = date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18 (MySQL DATETIME 格式)
$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today = date("m.d.y");                         // 03.10.01
$today = date("j, n, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day z ');  // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // It is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 15:16:08 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:17 m is month
$today = date("H:i:s");                         // 17:16:17
date('Y'); // 当前年份
date('m'); // 当前月份
date('d'); // 当前是几号
?>

<?php
echo strtotime("now"), "\n";  // 现在时间戳
echo strtotime("10 September 2000"), "\n"; // 2000年10月现在时间戳
echo strtotime("+1 day"), "\n";  // 距离现在一天后的时间戳
echo strtotime("-3 day"), "\n";  // 距离现在三天前的时间戳
echo strtotime("+1 week"), "\n"; // 距离现在一周后的时间戳
echo strtotime("-1 month"), "\n";// 距离现在一个月前的时间戳
echo strtotime("+1 year"), "\n"; // 距离现在一年后的时间戳
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";  // 距离现在1周2天4小时2秒后的时间戳
echo strtotime("next Thursday"), "\n";  // 下个星期三
echo strtotime("last Monday"), "\n";    // 本月的最后一个星期一
?>

获取前一天的时间戳:strtotime('-1 day') 或者 time() - 3600 * 24
获取今天凌晨0点的时间戳:strtotime(date("Y-m-d"), time())
获取今天某个时刻如6点半的时间戳: strtotime(data('Y-m-d')) + 6 * 3600 + 30 * 60
time() 获取当前Unix秒数时间戳,还可以使用 microtime() 获取当前 Unix 时间戳和微秒数,这个函数经常用来计算脚本运行的耗时
<?php
/**
 * 兼容php5.0版本以下
 */
function microtime_float(){
 list($usec, $sec) = explode(" ", microtime());
 return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();
usleep(100);  // 睡一小会儿
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "耗时: $time 秒\n";
?>

<?php
$lastday = mktime(0, 0, 0, 3, 0, 2000);
echo strftime("Last day in Feb 2000 is: %d", $lastday);
$lastday = mktime(0, 0, 0, 4, -31, 2000);
echo strftime("Last day in Feb 2000 is: %d", $lastday);
?>

About

When I was young
I'd listen to the radio
Waiting for my favorite songs
When they played I'd sing along
It made me smile
Those were such happy times
And not so long ago
How I wondered where they'd gone
But they're back again
Just like a long lost friend
All the songs I loved so well