How to convert date to timestamp in PHP?

2018-12-31 07:45发布

How do I get timestamp from e.g. 22-09-2008?

19条回答
伤终究还是伤i
2楼-- · 2018-12-31 08:09

Using mktime:

list($day, $month, $year) = explode('-', '22-09-2008');
echo mktime(0, 0, 0, $month, $day, $year);
查看更多
大哥的爱人
3楼-- · 2018-12-31 08:09

If you want to know for sure whether a date gets parsed into something you expect, you can use 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

It's obvious in this case, but e.g. 03-04-2008 could be 3rd of April or 4th of March depending on where you come from :)

查看更多
梦醉为红颜
4楼-- · 2018-12-31 08:11
<?php echo date('M j Y g:i A', strtotime('2013-11-15 13:01:02')); ?>

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

查看更多
人间绝色
5楼-- · 2018-12-31 08:14

If you're looking to convert a UTC datetime (2016-02-14T12:24:48.321Z) to timestamp, here's how you'd do it:

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);
查看更多
无色无味的生活
6楼-- · 2018-12-31 08:15

Be careful with functions like strtotime() that try to "guess" what you mean (it doesn't guess of course, the rules are here).

Indeed 22-09-2008 will be parsed as 22 September 2008, as it is the only reasonable thing.

How will 08-09-2008 be parsed? Probably 09 August 2008.

What about 2008-09-50? Some versions of PHP parse this as 20 October 2008.

So, if you are sure your input is in DD-MM-YYYY format, it's better to use the solution offered by @Armin Ronacher.

查看更多
倾城一夜雪
7楼-- · 2018-12-31 08:16

PHP's strtotime() gives

$timestamp = strtotime('22-09-2008');

Which does work with the Supported Date and Time Formats Docs.

查看更多
登录 后发表回答