I have a date in the following format
MM-DD-YYYY
How can I convert this to UNIX time in PHP
Thanks
Having a small problem
$date = strtotime($_POST['retDate']);
print $date; //Prints nothing
print $_POST['retDate']; //Prints 08-18-2009
If the format is always like that, I'd would try something like:
list($m,$d,$y) = explode('-', '08-18-2009');
$time = mktime(0, 0, 0, $m, $d, $y);
print date('m-d-Y', $time);
As for your example, the problem is the function fails. You should check it like so:
if(($time=strtotime('08-18-2009'))!==false)
{
// valid time format
}
else
echo 'You entered an invalid time format';
Use strtotime:
$str = "03-31-2009";
$unixtime = strtotime($str);
or you can use php date obyek to do that, like this
$tgl = "30-12-2013";
$tgl2 = DateTime::createFromFormat('d-m-Y', $tgl);
print_r($tgl2);
echo($tgl2->format('Y-m-d'));
i hope this can help...
Since these answers and comments were provided, PHP has updated to include a native function that suits this situation perfectly. Check out PHP's DateTime object here. This includes a createFromFormat
method that will do as requested. In this particular example:
$date = DateTime::createFromFormat('j-M-Y', $_POST['retDate']);
From there, you can format it as desired or perform any other date operations:
echo $date->format('Y-m-d');
And that's it! Keep in mind that this is only provided in PHP 5.3.0
or higher!