1

i have a strange questions. In my php page i try to print dates with php function and javascript function. My code is:

// 04 09 2013 09:47:28
<script>document.write(new Date());</script>
// 04 09 2013 09:48:17
<?php echo date('d m Y H:i:s');?>

Why the dates are not equal, but there is a litte second of difference?

I would have same dates beetween php and javascript.

---UPDATE CODE---

function startCounter(){
    start = new Date(<?php echo time(); ?> * 1000);
    end = new Date(<?php echo $end_ts; ?> * 1000);
    timer = setInterval(updateCounter, refreshInterval);
}

function updateCounter(){
var now = new Date();
    var distance = new Date(end - now);
}

Thank you very much.

5
  • time difference between your server and the computer your browser lives on? Commented Sep 4, 2013 at 7:55
  • Are JavaScript and PHP executed in the same computer? Commented Sep 4, 2013 at 7:56
  • Javascript in my browser, php in remote server Commented Sep 4, 2013 at 7:56
  • 1
    @Mike - So you've just answered your question. Most clocks are not atomic clocks ;-) Commented Sep 4, 2013 at 7:57
  • @Mike - Your question has already been answered. Please don't edit it to ask a new question, use the Ask Question button instead. (Though you haven't really asked a question, you've merely posted some code.) Commented Sep 4, 2013 at 8:27

2 Answers 2

1

First of all you need to understand the time being printed by php is the server time and time being printed by javascript is your local computer time. If the time between those 2 is different then it can show different time.

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

1 Comment

Add to that the time it takes for the server to actually send the page over to the client, who will then render the page, parse the JS, and execute the code, and you'll never get the exact same time, even if both clocks were set to the same time
0

Like others said, javascript time is client time and php time is server time. To solve the problem try something simliar to:

<? $time = time(); ?>
<script>document.write(new Date(<?=$time*1000?>));</script>    
<?=date('Y-m-d H:i:s', $time')?>

2 Comments

Don't use document.write... just don't
@EliasVanOotegem I totally agree with you. I just copied the authors code :)

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.