Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JavaScript new Date() to php DateTime()

I have 2 fields in HTML:

<input id="datum" type="date">
<input id="uhrzeit" type="time">

JavaScript:

var datumUhrzeit = new Date($("#datum").val()+","+$("#uhrzeit").val());
console.log(datumuhrzeit);

 "Tue Aug 18 2015 16:45:00 GMT+0200 (Mitteleuropäische Sommerzeit)"

How can I convert "Tue Aug 18 2015 16:45:00 GMT+0200 (Mitteleuropäische Sommerzeit)" in PHP to a DateTime, so that I can save it to postgresql?

like image 321
Suisse Avatar asked Jul 03 '15 16:07

Suisse


1 Answers

You can get unix timestamp from Date object as follows (see Date.prototype.getTime)

var timestamp = '@' + Math.round(datumUhrzeit.getTime()/1000);

Then when sent on server simply create new datetime object

$datumUhrzeit = new DateTime($timestamp);

If you can't use javascript to create timestamp and you get the the data from form directly you can do something like this, remember to set the timezone:

$datum = $_GET['datum'];
$uhrzeit = $_GET['uhrzeit'];
$datumUhrzeit = DateTime::createFromFormat('Y-m-d H:i:s', $datum . ' ' . $uhrzeit, new DateTimeZone('Europe/Berlin'));

Now as you have saved your date to the database and retrieved it, you can send it back

print $datumUhrzeit->format('U'); // This will print the time as unix timestamp

After that you would create your javascript date object with just the timestamp

var datumUhrzeit = new Date(timestamp * 1000); // timestamp from above

If you for some reason don't want to use unix timestamp you can print it in desired format with format method. Remember to set the timezone beforehand

$datumUhrzeit->setTimezone(new DateTimeZone('Europe/Berlin'));
print $datumUhrzeit->format('Y-m-d H:i:s');

Because javascript doesn't work well with timezones I would advocate you to use unix timestamps when you can. This way you have less problems with timezones.

like image 177
Skydda Avatar answered Sep 21 '22 09:09

Skydda