strtotime
在 php 中有一些很棒的函数可以将人类可读的日期转换为时间戳。
第一个魔术函数叫做 strtotime(字符串到时间):给它你的日期,你得到一个 UNIX 时间戳!让我们看一些例子:
echo strtotime('2008-04-12 13:24');
echo strtotime('12 april 2008 13:24');
echo strtotime('12.04.2008 13:24');
更强大的是,strtotime可以识别一些关键字:
echo strtotime('now');
echo strtotime('+4 days');
echo strtotime('+1 month');
echo strtotime('next monday');
echo strtotime('+2 weeks 3 days 4 hours 23 minutes');
strtotime 的第二个参数是一个时间戳,它的默认值是实际的时间戳(time())。所以 echo strtotime('+4 days') 是相对于当前时间的。当然你也可以给strtotime你的mysql日期! (注意你也可以使用mysql函数UNIX_TIMESTAMP,它会使用更多的资源)。
为了比较日期,现在只是一个细节:
// your first date coming from a mysql database (date fields)
$dateA = '2008-03-01 13:34';
// your second date coming from a mysql database (date fields)
$dateB = '2007-04-14 15:23';
if(strtotime($dateA) > strtotime($dateB)){
// bla bla
}
比子字符串更好,不是吗?!
这里只是另一个例子,不是相对于当前日期,而是相对于特定日期:
strtotime('23 hours ago', strtotime('2005-04-13 14:00'));
这意味着相对于第二个给定日期的 23 小时前,它必须是时间戳。
用户手册没有给出支持的日期格式的完整描述。 Strtotime('dd/mm/YYYY') 不起作用,它只适用于 mm/dd/YYYY 格式。
dd/mm/YYYY格式的日期,可以使用explode()函数将其转换为YYYY-mm-dd,但我认为有更好的解决方案。
$date = '25/05/2010';
$date = str_replace('/', '-', $date);
echo date('Y-m-d', strtotime($date));