PHP Converting a date to a timestamp
How do I convert "9/7/2009" into a timestamp, such as one from time()
? Do I use strt开发者_C百科otime()
?
Yes you can use strtotime()
for that
$time = strtotime('9/7/2009');
echo $time; // 1252278000
This will assume a format of mm/dd/yyyy so don't try it with UK-style dd/mm/yyyy dates.
To go the other way, use date()
$date = date('n/j/Y', $time);
echo $date; // 9/7/2009
strtotime() is correct.
http://php.net/manual/en/function.strtotime.php
You can test to be sure by putting the returned timestamp back in the date() function.
<?php echo date("m-d-Y",strtotime("9/7/2009")); ?>
Use strptime
if you want to be more precise about the format to parse, and remember that when people in the rest of the world see "9/7/2009" they read 9th July 2009, not 7th September 2009.
A newer way to do this as of PHP 5.3 is to use the DateTime class with the getTimestamp()
method:
$datetime = new DateTime('9/7/2009');
echo $datetime->getTimestamp();
See it in action
精彩评论