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


当前回答

如果你想把UTC日期时间(2016-02-14T12:24:48.321Z)转换成时间戳,下面是你该怎么做:

function UTCToTimestamp($utc_datetime_str)
{
    preg_match_all('/(.+?)T(.+?)\.(.*?)Z/i', $utc_datetime_str, $matches_arr);
    $datetime_str = $matches_arr[1][0]." ".$matches_arr[2][0];

    return strtotime($datetime_str);
}

$my_utc_datetime_str = '2016-02-14T12:24:48.321Z';
$my_timestamp_str = UTCToTimestamp($my_utc_datetime_str);

其他回答

这个方法在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

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

对于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 echo date('M j Y g:i A', strtotime('2013-11-15 13:01:02')); ?>

http://php.net/manual/en/function.date.php

$time = '22-09-2008';
echo strtotime($time);

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