This question already has an answer here:
-
php dateTime::createFromFormat in 5.2?
6 answers
I am using the following code to convert user input into a mysql timestamp.
$datetime = DateTime::createFromFormat('m/d/Y g:i a', "{$exp}");
$timestamp = $datetime->format('Y-m-d H:i:s');
where $exp
would equal something like: 06/12/2013 6:41 pm
This works fine on my local server which is running PHP 5.4.3, but when I upload the same script onto my hosting server, It does not want to run this part probably because of the difference in PHP versions.
How would I go about fixing this or an alternative to it? Thanks!
You could extend the DateTime class and implement createFromFormat()
yourself like this:-
class MyDateTime extends DateTime
{
public static function createFromFormat($format, $time, $timezone = null)
{
if(!$timezone) $timezone = new DateTimeZone(date_default_timezone_get());
$version = explode('.', phpversion());
if(((int)$version[0] >= 5 && (int)$version[1] >= 2 && (int)$version[2] > 17)){
return parent::createFromFormat($format, $time, $timezone);
}
return new DateTime(date($format, strtotime($time)), $timezone);
}
}
$dateTime = MyDateTime::createFromFormat('Y-m-d', '2013-6-13');
var_dump($dateTime);
var_dump($dateTime->format('Y-m-d'));
This will work in all versions of PHP >= 5.2.0.
See here for a demo http://3v4l.org/djucq
To make a timestamp from a particular date...:
$time = "06/12/2013 6:41 pm";
$format = "%m/%d/%Y %l:%M %P";
$ts = strptime($time, $format);
$ts = mktime($ts['tm_hour'], $ts['tm_min'], $ts['tm_sec'], $ts['tm_mon'], $ts['tm_mday'], ($ts['tm_year'] + 1900));
after you can use like you want:
$mysql_timestamp = date("Y-m-d H:i:s", $ts);