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


当前回答

<?php echo date('U') ?>

如果你愿意,把它放在一个MySQL输入类型时间戳中。上面的代码运行得很好(仅适用于PHP 5或更高版本):

<?php $timestamp_for_mysql = date('c') ?>

其他回答

以下是我的做法:

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'];

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

我使用的格式是: $presentDateTime = strtotime(date('Y-m-d H:i:s'));

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

http://nl3.php.net/manual/en/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)

如果已经有了该格式的日期,则只需要在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