1

I'm sending JS date object to PHP in ajax. Then I write it to mySql. Should I convert date object to string in javascript before sending? Or can I convert it in PHP - I prefer this solution. Which way is correct one?

PS. I'm using PDO to write it in DB.

5
  • 3
    you can't send "code" objects through ajax. one way or another, you're serializing your JS date object into a string, so might as well serialize it into something easy to parse, e.g. a unix timestamp (which in JS is in milliseconds).
    – Marc B
    Dec 15, 2014 at 19:23
  • You can't send objects, so either way it's going to be a string when it reaches the server.
    – adeneo
    Dec 15, 2014 at 19:23
  • Keep them as intergers of some unit since the unix epoch
    – Paul S.
    Dec 15, 2014 at 19:23
  • send timestamp... like Date.now() or (new Date()).getTime()
    – vp_arth
    Dec 15, 2014 at 19:25
  • Regardless of which way you send your date it will be a string. You can do it in any format as long you know how you will parse back into a date that can be parsed by your db engine of choice.
    – Konstantin
    Dec 15, 2014 at 19:35

2 Answers 2

7

In most cases you will have to convert your JS Date to string. Good ways are:

var d = new date();
var iso_date_string = d.toISOString(); 
// produces "2014-12-15T19:42:27.100Z"
var locale_date_string = d.toLocaleDateString();
// produces "12/15/2014"

toLocaleDateString() has a lot of localization options.

And you can convert any valid date string to date in PHP by

$date = date( "Y-m-d H:i:s", strtotime("2014-12-15T19:42:27.100Z") );
// produces "2014-12-15 20:42:27"
$date = date( "Y-m-d", strtotime("12/15/2014") );
// 2014-12-15

"Y-m-d H:i:s" or Y-m-d can be any supported date and/or time format

0

POST and GET both submit strings to the server, read answer here: What are the data type limitations of the POST and GET HTML Form Methods?

However in practice whether you must manually convert depends on your framework, for example jQuery will convert objects to strings for you before sending to server (sounds like what you want).

Still other end-to-end frameworks may handle data binding in such a way that you don't need to manually convert either in browser or on server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.