夏期劇場
夏期劇場

Reputation: 18325

PHP Date to Javascript Date becomes Time Difference?

I'm using JS DataTable and the Date Column must be sortable. But it can't sort as JS assume the Dates imported as the Strings. (It doesn't sort in actual chronological order. Just in string order)

Then as i googled, i start realized that JS can only sort JS Dates. Means, i need to convert PHP Date into JS Dates.

But i can't get it properly yet. What i did is:

<script>
    var jsDate = new Date(
                        <?php echo $phpDate_y; ?>,
                        <?php echo $phpDate_m; ?>,
                        <?php echo $phpDate_d; ?>
                    ); // $phpDate will be "2012-04-30";
</script>

But on rendering, the jsDate is transformed as:

Thu Oct 03 1935 00:00:00 GMT+0730 (MALST)

FAR DIFFERENT!!
And, my timezone location is Singapore.
Is there any other proper way pls :(

Upvotes: 1

Views: 367

Answers (2)

Eugene
Eugene

Reputation: 1730

Try to use date_default_timezone_set('America/Los_Angeles');

first line in your PHP scripts.

php.net/manual/en/function.date-default-timezone-set.php

Upvotes: 1

peacemaker
peacemaker

Reputation: 2591

You can pass a full date string to the JS Date object to construct it so try passing $phpDate in one of the ISO date formats into the Date constructor instead of splitting it the way you're doing it.

// $phpDate = '2012-08-17 12:29:06'
var jsDate = new Date("<?php echo $phpDate; ?>");

Upvotes: 2

Related Questions