In the user interface, i have a text field to enter date in dd/mm/yyyy format and there is another textbox for time in hh:mm format and another dropdown box to specify am or pm. All these three fields will let the user to enter the date,time and am/pm manually. I prefered to use this primitive method as per the requirement of the project.
Now i want all these values to be added in mysql in timestamp format to make it easier to fetch and manipulate. Please suggest me how can i achieve this.
<?
$date = '21'.'/'.'11'.'/'.'2011';
$time = '12'.':'.'00';
$ampm = "am";
$dt = DateTime::createFromFormat(
'd/m/Y h:i a',
sprintf('%s %s %s', $date, $time, $ampm),
new DateTimeZone('Country/Region'));
$mysqlDateString = $dt->format('Y-m-d H:i:s');
?>
Use mktime in conjunction with the correct format to date by sending your user input to explode, like so:
Now
$mysql_timestampis a valid entry for a datetime column.If you need a UNIX timestamp, just remove the call to
date, like so:Demo
Edit: As per Phil’s comments below, be sure to set a correct timezone with date_default_timezone_set.