0

I am trying to get current server date-time in javascript. So I am passing php date timestamp to javascript date function but I am getting one day difference in date of javascript. Below is my code:

function showRemaining() {
            <?php
             $current_date = date("m/d/y H:i:s");
             $date = strtotime($current_date) * 1000;
            ?>
            alert('<?php echo $current_date;?>'); //alerts 12/04/15 05:42:14            
            var now = new Date(<?php echo $date;?>);
            alert(now); //alerts Thu Dec 03 2015 21:42:14 GMT-0800 (Pacific Standard Time)
    }

I want it to display today's date i.e Dec 4 .

Brainy Prb
  • 433
  • 1
  • 9
  • 22
  • Set the timezone appropriately! – Thamilhan Dec 04 '15 at 05:47
  • @MyWay My timezone is set appropriately in PHP as date_default_timezone_set('America/Toronto'); and as I already stated in my problem above that PHP is giving me correct time according to the timezone set (i.e. 4th december) but on passing it to javascript date object it gives me december 3. So thats my issue. – Brainy Prb Dec 04 '15 at 05:51
  • see this i hope it will help you [javascript-date-object-always-one-day-off](http://stackoverflow.com/questions/7556591/javascript-date-object-always-one-day-off) – shubham715 Dec 04 '15 at 06:01

2 Answers2

0

Have you thought about the difference in the timezone in your own PC? I had the same problem with mongoDB, It just kept setting the time 2 hours back.

Amsterdam with daylightsavings = + 2 hours.

Just check your time settings on your PC and if they are okay, add or subtract a couple of hours from the time until you get the correct date.

sillysicko
  • 126
  • 7
0

Note that both of them display exactly the same time (05:42:14 UTC = 21:42:14 GMT-0800).

Based on my quick search, there's no easy way to tell JavaScript to print the date in some other timezone, than the local one.

So, depending on your use case:

  1. If you just want to print current date, then generate the string on the PHP side, where the time zone is under your control.

  2. If you want the Date object to contain correct date, then it already does (it was in fact 21:42 in PST when you posted your question).

  3. If you want JavaScript to hold the correct date, but also be capable of printing it in your server's timezone, what you can do is send your server's timezone alongside the time to the client, then detect the client's timezone (var offset = new Date().getTimezoneOffset();), compute their difference, and add that many hours to the date you received from the server. Then just use some date format that does not print the timezone (Many ways of doing that are described here).

P.S. unrelated to your question, but this:

$current_date = date("m/d/y H:i:s");
$date = strtotime($current_date) * 1000;

can be replaced with:

time() * 1000
Community
  • 1
  • 1
Ishamael
  • 12,583
  • 4
  • 34
  • 52