Jump to content

Problem with PHP Time and Javascript


hitk

Recommended Posts

I am currently using the below code which is not working.

<script type="text/javascript">
function GetIst() { 
var d = new Date()
var gmtHours = -d.getTimezoneOffset()*60;
document.write(+ gmtHours);
}
</script>

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("mysql2", $con);
$reminder = "<script language=javascript>GetIst();</script>"; 
$currentdate = date("Y-m-d");  
$res = mysql_query("SELECT * FROM schedule WHERE sch_date >= '$currentdate' ORDER BY timestmp ASC limit 20");
while ( $row = mysql_fetch_array($res) ) {
   echo '<br />'.date('H:i', strtotime("+$reminder seconds",strtotime($row["sch_time"]))); 
}

?>

 

It gives all times as 00:00. It should be like 12:30 or 04:30

 

But when excecute below it does work.

 

<?php 
$time_current = "<script language=javascript>GetIst();</script>"; 
echo "". $time_current; 
?>

 

Now, I cannot use the second code because I also need to offset time for client time zone.

 

What I believe error could be at

 

   echo '<br />'.date('H:i', strtotime("+$reminder seconds",strtotime($row["sch_time"]))); 

 

Help would be appreciated.

Link to comment
https://forums.phpfreaks.com/topic/208274-problem-with-php-time-and-javascript/
Share on other sites

You cannot run a Javascript function from PHP.  PHP runs on the SERVER before the page is sent to the browser.  Javascript runs on the CLIENT (browser) after PHP is completely done and exited. There is no way that I know of, to "magically" get the client's timezone. I sure wish they would add it to the HTTP specifications, have the client send current time zone in a header with the original GET request, but it is not there.

 

The best you can do, is show the time and indicate the timezone that you are using for the display. Then give the user an option to specify their timezone.  Once the user has selected a timezone, store it in a cookie so you can get it next time without asking them.  If these are registered users, you can store it in the database with their profile and carry it in a SESSION.

 

If there is a form the user completes and submits before getting to this page, you could have Javascript on that page to populate a hidden field with the DST value so you can use it on the page that processes the form. If the user does not have Javascript enabled, the value would be empty and then you use the cookie idea above.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.