9

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?

1

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

8 Comments

in PHP: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (1436525100000) at position 10 (0): Unexpected character
Sorry about that :) check it now. You have to divide getTime output with 1000 since it returns milliseconds and unix timestamp uses seconds. Also it requires @ character in front of the timestamp.
in javascript: 2015-07-10 12:00:00 in php: 2015-07-10 10:00:00 Should I just add 2hours in php?? what a bricolage!
The javascript returns an unix timestamp which is UTC time. When that is parsed in php it shows the time in UTC timezone. You can change the timezone for the DateTime object using php.net/manual/en/datetime.settimezone.php
so how can I get the right time back in Javascript? $datumUhrzeit = new DateTime("2015-07-10 11:00:00",new DateTimeZone('UTC')); echo date_format($datumUhrzeit, 'Y-m-d H:i'); So how can I get from 11:00:00 to 13:00:00 (the time whic I had in my html field on the start)
|
1

You can use this javascript function to convert the dateObject or date string to your desired format:

/**
 * Formats a dateObject or date string to Y-m-d date
 * Example: Converts  dateObject or date string  Sat Aug 19 2017 00:00:00 GMT+0530 (India Standard Time)   TO  2017-08-19   
 */
function format_date( date )
{
    if (typeof date == "string")
    {
        date = new Date(date);
    }

    var year = date.getFullYear();
    var month = (1 + date.getMonth()).toString();
    month = month.length > 1 ? month : '0' + month;

    var day = date.getDate().toString();
    day = day.length > 1 ? day : '0' + day;

    return year+'-'+month+'-'+day;
}

var dateString = 'Tue Aug 18 2015 16:45:00 GMT+0200 (Mitteleuropäische Sommerzeit)';

var formattedDate = format_date(dateString);//returned formatted date is 2015-08-18

Then you can pass this formatted date to your PHP code where you can use function strtotime to convert this date to your desired format. For ex:

$myFormattedDate = date('d-m-Y', strtotime($_REQUEST['formattedDate']));

2 Comments

I want to do same thing using php
No need got it $cheque_date = substr($request['cheque_date'], 0, strpos($request['cheque_date'], '(')); $insertArray['cheque_date'] = date('Y-m-d', strtotime($cheque_date));
0

You can do something like

$datumUhrzeit = 'Tue Aug 18 2015 16:45:00 GMT+0200 (Mitteleuropäische Sommerzeit)';
$datumUhrzeit = substr($datumUhrzeit, 0, strpos($datumUhrzeit, '('));
$resultDate = date('Y-m-d h:i:s', strtotime($datumUhrzeit));
echo $resultDate;

2 Comments

no that didn't work, I got "1970-01-01 01:00:00" in the database.
what is your table structure
-1

try this one

 function myFunction() {
      var content =  document.getElementById("datum").value+","+document.getElementById("uhrzeit").value;
  console.log(content);

  }

3 Comments

@user3037960 Thats because this code is a mess. Check stackoverflow.com/a/3005959/156811
@user3037960 You may think its the same code, but its not. He missed the $ in strtotime(datumUhrzeit) when copying the answer from the other question, in this state the code won't work as expected. I won't edit this answer for this reason, and also because its poorly written.
at this point it is not important that code from where copied , written the goal is to provide solution to the question......

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.