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


当前回答

对于PHP >=5.3, 7和8,这可能工作-

$date = date_parse_from_format('%Y-%m-%d', "2022-11-15"); //here you can give your desired date in desired format. 
                                                           //just need to keep in mind that date and format matches.

$timestamp = mktime(0, 0, 0, $date['month'], $date['day'], $date['year'] + 2000); //this will return the timestamp

$finalDate= date('Y-m-d H:i:s', $timestamp); //now you can convert your timestamp to desired dateTime format.

文档:

date_parse_from_format () mktime () 日期()

其他回答

这个方法在Windows和Unix上都可以工作,并且是时区感知的,如果您使用日期,这可能是您想要的。

如果你不关心时区,或者想使用你的服务器使用的时区:

$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
if ($d === false) {
    die("Incorrect date string");
} else {
    echo $d->getTimestamp();
}

1222093324(这将取决于您的服务器时区…)

如果要指定在哪个时区,请在这里指定EST(与纽约相同)。

$d = DateTime::createFromFormat(
    'd-m-Y H:i:s',
    '22-09-2008 00:00:00',
    new DateTimeZone('EST')
);

if ($d === false) {
    die("Incorrect date string");
} else {
    echo $d->getTimestamp();
}

1222093305

或者如果你想使用UTC。(与“GMT”相同。)

$d = DateTime::createFromFormat(
    'd-m-Y H:i:s',
    '22-09-2008 00:00:00',
    new DateTimeZone('UTC')
);

if ($d === false) {
    die("Incorrect date string");
} else {
    echo $d->getTimestamp();
}

1222093289

无论如何,在将字符串解析为结构化数据时,严格总是一个好的起点。这样可以省去将来调试的麻烦。因此,我建议始终指定日期格式。

下面是一个非常简单而有效的解决方案,使用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);

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

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

对于PHP >=5.3, 7和8,这可能工作-

$date = date_parse_from_format('%Y-%m-%d', "2022-11-15"); //here you can give your desired date in desired format. 
                                                           //just need to keep in mind that date and format matches.

$timestamp = mktime(0, 0, 0, $date['month'], $date['day'], $date['year'] + 2000); //this will return the timestamp

$finalDate= date('Y-m-d H:i:s', $timestamp); //now you can convert your timestamp to desired dateTime format.

文档:

date_parse_from_format () mktime () 日期()

使用PHP函数strtotime()

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

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