Updating Time in Local Storage - php

I am trying to connect to the server every minute and pass in the variable of the current time, which would be the lastUpdate. On the server side php file, I plan to compare the passed in time variable with a TIMESTAMP in the database rows; much like if (time1-time2 > certain value)... So far the javascript code is:
var time;
var timer_is_on = 0;
localStorage.lastUpdate = 0;
localStorage.numUpdates = 0;
function timedCount()
{
localStorage.lastUpdate = new Date();
//connect to server
contactServer(localStorage.lastUpdate);
currentCount=currentCount+1;
time=setTimeout("timedCount()",60000);
}
My question is whether I am doing this correctly. I am declaring localStorage.lastUpdate as new Date() and I'm not sure whether this is correct? I have tried the loop and every minute lastUpdate seems to be the same date and time.
My last question is whether I can actually compare the two time formats from javascript and php. In the SQL timestamp, the format is 2012-03-20 11:14:40 while the date format from the javascript new Date() is Tue Mar 20 2012 12:32:44 GMT-0400 (Eastern Daylight Time).
Any information would be helpful, thanks!

Be careful when you use time. Your server time may be different from your client time. The best for you is to store the date of the last request in $_SESSION['last'].
With this solution, all your problems are not anymore. Your PHP set the date, so it is the same reference, and it's in a good format.
Just keep your timeout on the client side:-)

Use new Date().getTime() to return a UNIX timestamp; that is, the number of seconds since Jan 1st, 1970. This makes it much easier to compare with other times.
localStorage.lastUpdate = new Date().getTime();
Will return something like this: 1332266002.
The PHP equivalent is simply time().
And to convert that UNIX timestmap into a MySQL TIMESTAMP, use MySQL's FROM_UNIXTIME function.

Related

How to get time with respect to MySQL timestamp, in ActionScript 3?

I want to show an ActionScript 3.0 Timer, with respect to a timestamp gotten from MySQL.
So suppose MySQL (PHP) returns a string like $my_birthday="2013-05-22 12:30:45"
I got it from ActionScript by a URLLoader, and I want to show the timer like this:
My age:
01 hours 01 minutes 42 seconds
What function should I use in:
public function timerHandler(e:TimerEvent)
{
log_textfield.text = String((new Date()).time) - my_birthday; // I need to convert the Date().Time to unix timestamp I guess, and a function for time difference.
}
This answer has a TimeSpan class that you may want to use. The code below should do what you need to get the TimeSpan where you can get the parts you need to display. I don't have Flash on this computer though to test, so your mileage may vary :)
// new Date() is allergic to dashes, it needs slashes.
my_birthday = my_birthday.replace('-', '/');
var sinceBirthday = TimeSpan.fromDates(new Date(), new Date(my_birthday));

javascript function new Date() not working

My problem is as follows:
I want to display nepalese standard time in my website,so i set default timezone of my
website to 'Asia/kathmandu' using command: php_value date.timezone 'Asia/kathmandu' in htaccess file.
when i display time using any php functions like strftime() or date() ,it shows the nepalese standard time,
But when i use javascript function new Date(<?php echo time()*1000; ?>),it displays
the time of my personal pc i am using to view my website.
How can i display correct time using javascript date functions? Can anybody help me out?
Your issue is because javascript (actually ECMAScript) date objects are based on a UTC time value. When you do:
new Date(<?php echo time()*1000; ?>)
you are passing a UTC millisecond time value to the Date constructor, which then creates a date object. When you use the usual Date methods to format a string, or use Date.prototpye.toString or Date.prototype.toLocaleString, you will get a string based on the client's locale. Note that all these strings are implementation dependent and vary widely for the locale version.
If you want the timezone of the server, then use the server to set it. Or you can send a time zone offset in minutes to be applied to the local time to get back to Nepalese Standard Time (UTC + 5:45). Note that in ECMAScript, the time zone offset is minutes to be added to the local time to get UTC, whereas it is more normal to define the offset in minutes to be added to UTC to get the local time.
So to get NST:
function toNST(timeValue) {
function z(n) {return (n<10? '0' : '') + n}
var d = new Date();
var nstOffset = 5 * 60 + 45;
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() + nstOffset);
return z(d.getHours()) + ':' + z(d.getMinutes()) + ':' + z(d.getSeconds());
}
alert(toNST(+(new Date()))); // about 11:07:17 at the moment
Use
new Date(Date.NPT(year, month, day, hour, minute, second))
Call the time via ajax from your server. That has the advantage of a better code maintanance. If you change the time again (e.g. if you want to use the code for another location) you have only to change the time in .haccess.

How to show a Unix-time in a local time format

I have a php variable say $expTime (which has a unixtime say-1359683953) . I want to display this variable on the client side(in a proper time format according to his local time) . I am so confused between the UTC ,GMT , DST all that things. Can anyone suggest a solution for this using php or javascript please.
when I am using echo date('h:i M d/y',$expTime) it is showing me a wrong time.
How I am saving the time to database:
var exp_day= parseInt($("#exp_day").val());
var exp_hrs= parseInt($("#exp_hrs").val());
var exp_min= parseInt($("#exp_min").val());
var exp_time = (exp_day*24*60*60) + (exp_hrs*60*60) + (exp_min*60) ;
then I posted the exp_time using ajax to a php file -
$expTime = time() + $_POST["exp_time"];
What I am retrieving from the database is $expTime . This $expTime I want to display it on the all the clients system according to there local time zone (also by making sure the day light saving)
Use DateTime with timezones:
$datetime = new DateTime('#1359683953');
echo $datetime->format('h:i M d/y') . "<br>";
$datetime->setTimezone(new DateTimeZone('America/Los_Angeles'));
echo $datetime->format('h:i M d/y');
See it in action
UNIX time values are usually UTC seconds since epoch. Javascript time values are UTC milliseconds since the same epoch. The ECMA-262 Date.prototype.toString method automatically generates a string representing the local time and takes account of daylight saving if it applies.
You can also use Date methods to create your own formatted string, they also return local time and date values. There are also UTC methods if you want to work in UTC.
To do this on the client, just provide a UTC time value from the server and then all you need in javascript is:
var timeValue = 1359683953; // assume seconds
var date = new Date(timeValue * 1000); // convert time value to milliseconds
alert(date); // Fri 01 Feb 2013 11:59:13 GMT+1000

Converting string into Date() in JavaScript

How do I convert this timestamp from php into a javascript Date() object?
This is how I grab the time:
$timestart = time();
and I parse this to a javascript function and I want to convert it into a JavaScript date object.
help, all this date stuff confuses me quite a bit.
thanks,
If val contains your PHP value which is
the current time measured in the number of seconds since the Unix Epoch
then you just need this:
var timestart = new Date(val * 1000);
JavaScript uses the same base time as UNIX systems (midnight on 01/01/1970) but measured in milliseconds rather than seconds.
Solution here :
Convert a Unix timestamp to time in JavaScript
Substring the parts of the timestamp you need to create the Date. Then initialise like so,
var d = new Date(year, month, date);
This is a cross browser implementation.

Convert all dates in PHP to local time

The server my PHP script is running on is set to UTC. I can't seem to figure out a way to set all dates to the browser's timezone. All dates displayed are formatted using PHP's date() function.
I know that via JavaScript's getTimezoneOffset() function, I can get the browser's current UTC offset (-4, in my case). How can I tell PHP to use this offset? I can use date_default_timezone_set(), but how do I convert an offset, say -4, to a time zone string, say America/New_York?
Note: The server is running PHP 5.1.6 (with no DateTime class) and I am using CodeIgniter.
As per the comment above- you could use a cookie...:
Javascript:
var today = new Date();
function SetCookie(cookieName,cookieValue,nDays) {
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString();
}
SetCookie("datecookie", today, 30);
window.location.href=window.location.href
PHP:
echo date("m d Y", strtotime($_COOKIE['datecookie']));
Because Javascript is client based and PHP is server based, they will not communicate. To tell the server the browser time, you will need to send information from the client, perhaps via Ajax, posting the browser time. The target PHP script should then handle/output this as appropriate. One other (obtuse) option is to attempt to geolocate the user based on IP, then guesstimate the correct time for that location- however this is inefficient for this purpose.
"I know I can use date_default_timezone_set(), but how do I convert an offset, say -4, to a time zone string, say America/New_York?"
Simply look at the comments associated with the documentation for that function. Comment #99006 does the work for you. You just need to get the timezone offset from the user.

Categories