如何从例如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 () 日期()

其他回答

如果你想确定一个日期是否被解析成你想要的,你可以使用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日,这取决于你来自哪里:)

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。

如果你想把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);

使用PHP函数strtotime()

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

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

对于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 () 日期()