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


当前回答

如果已经有了该格式的日期,则只需要在PHP中调用“strtotime”函数。

$date = '22-09-2008';
$timestamp = strtotime($date);
echo $timestamp; // 1222041600

或在单行中:

echo strtotime('22-09-2008');

简短而简单。

其他回答

function date_to_stamp( $date, $slash_time = true, $timezone = 'Europe/London', $expression = "#^\d{2}([^\d]*)\d{2}([^\d]*)\d{4}$#is" ) {
    $return = false;
    $_timezone = date_default_timezone_get();
    date_default_timezone_set( $timezone );
    if( preg_match( $expression, $date, $matches ) )
        $return = date( "Y-m-d " . ( $slash_time ? '00:00:00' : "h:i:s" ), strtotime( str_replace( array($matches[1], $matches[2]), '-', $date ) . ' ' . date("h:i:s") ) );
    date_default_timezone_set( $_timezone );
    return $return;
}

// expression may need changing in relation to timezone
echo date_to_stamp('19/03/1986', false) . '<br />';
echo date_to_stamp('19**03**1986', false) . '<br />';
echo date_to_stamp('19.03.1986') . '<br />';
echo date_to_stamp('19.03.1986', false, 'Asia/Aden') . '<br />';
echo date('Y-m-d h:i:s') . '<br />';

//1986-03-19 02:37:30
//1986-03-19 02:37:30
//1986-03-19 00:00:00
//1986-03-19 05:37:30
//2012-02-12 02:37:30

考虑到函数strptime()不适用于Windows, strtotime()可能会返回意外的结果,我建议使用date_parse_from_format():

$date = date_parse_from_format('d-m-Y', '22-09-2008');
$timestamp = mktime(0, 0, 0, $date['month'], $date['day'], $date['year']);

下面是一个非常简单而有效的解决方案,使用split和mtime函数:

$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);

这对我来说就像魔法一样。

DateTime API:

$dateTime = new DateTime('2008-09-22'); 
echo $dateTime->format('U'); 

// or 

$date = new DateTime('2008-09-22');
echo $date->getTimestamp();

过程式API也是如此:

$date = date_create('2008-09-22');
echo date_format($date, 'U');

// or

$date = date_create('2008-09-22');
echo date_timestamp_get($date);

如果由于使用了不受支持的格式而导致上述操作失败,则可以使用

$date = DateTime::createFromFormat('!d-m-Y', '22-09-2008');
echo $dateTime->format('U'); 

// or

$date = date_parse_from_format('!d-m-Y', '22-09-2008');
echo date_format($date, 'U');

请注意,如果您没有设置!,时间部分将被设置为当前时间,这与前四个不同,当您省略时间时将使用午夜。

还有一种替代方法是使用IntlDateFormatter API:

$formatter = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'GMT',
    IntlDateFormatter::GREGORIAN,
    'dd-MM-yyyy'
);
echo $formatter->parse('22-09-2008');

除非您正在使用本地化的日期字符串,否则更容易的选择可能是DateTime。

小心使用像strtotime()这样试图“猜测”您的意思的函数(它当然不会猜测,规则在这里)。

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

08-09-2008将如何解析?可能是2008年8月9日。

那2008-09-50呢?某些版本的PHP将此解析为20 October 2008。

所以,如果你确定输入的是DD-MM-YYYY格式,最好使用@Armin Ronacher提供的解决方案。