如何在PHP中将日期转换为时间戳?

时间:2020-03-06 14:31:47  来源:igfitidea点击:

我如何从例如获取时间戳22-09-2008

解决方案

使用mktime:

list($day, $month, $year) = explode('-', '22-09-2008');
echo mktime(0, 0, 0, $month, $day, $year);

PHP的strtotime()给出了

$timestamp = strtotime('22-09-2008');

与支持的日期和时间格式文档一起使用。

还有strptime(),它只需要一种格式:

$a = strptime('22-09-2008', '%d-%m-%Y');
$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900);

要小心使用诸如" strtotime()"之类的函数,这些函数试图"猜测"意思(当然,这里没有规则,我猜不到)。

实际上," 22-09-2008"将被解析为2008年9月22日,因为这是唯一合理的事情。

如何解析" 08-09-2008"?大概是2008年8月9日。

2008-09-50呢?某些版本的PHP会将其解析为2008年10月20日。

因此,如果我们确定输入的格式为DD-MM-YYYY,则最好使用@Armin Ronacher提供的解决方案。

如果我们知道格式,请使用strptime,因为strtotime会对格式进行猜测,但这可能并不总是正确的。由于Windows中未实现strptime,因此有一个自定义函数

  • http://nl3.php.net/manual/zh/function.strptime.php#86572

请记住,返回值" tm_year"是从1900开始的!并且" tm_month"为0-11

例子:

$a = strptime('22-09-2008', '%d-%m-%Y');
$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900)

这是我的做法:

function dateToTimestamp($date, $format, $timezone='Europe/Belgrade')
{
    //returns an array containing day start and day end timestamps
    $old_timezone=date_timezone_get();
    date_default_timezone_set($timezone);
    $date=strptime($date,$format);
    $day_start=mktime(0,0,0,++$date['tm_mon'],++$date['tm_mday'],($date['tm_year']+1900));
    $day_end=$day_start+(60*60*24);
    date_default_timezone_set($old_timezone);
    return array('day_start'=>$day_start, 'day_end'=>$day_end);
}

$timestamps=dateToTimestamp('15.02.1991.', '%d.%m.%Y.', 'Europe/London');
$day_start=$timestamps['day_start'];

这样,我们可以让函数知道我们使用的日期格式,甚至指定时区。

这是一个使用splitmtime函数的非常简单有效的解决方案:

$date="30/07/2010 13:24"; //Date example
list($day, $month, $year, $hour, $minute) = split('[/ :]', $date); 

//The variables should be arranged according to your date format and so the separators
$timestamp = mktime($hour, $minute, 0, $month, $day, $year);
echo date("r", $timestamp);

对我来说,它就像是一种魅力。