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


当前回答

以下是我的做法:

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

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

其他回答

如果你想确定一个日期是否被解析成你想要的,你可以使用DateTime::createFromFormat():

$d = DateTime::createFromFormat('d-m-Y', '22-09-2008');
if ($d === false) {
    die("Woah, that date doesn't look right!");
}
echo $d->format('Y-m-d'), PHP_EOL;
// prints 2008-09-22

在这种情况下很明显,但是例如03-04-2008可能是4月3日或3月4日,这取决于你来自哪里:)

使用mktime:

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

以下是我的做法:

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

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

使用PHP函数strtotime()

echo strtotime('2019/06/06');

date -格式化本地时间/日期

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

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

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