Static countdown with javascript/php, how? - php

var austDay = new Date("May 18, 2012 00:00:00");
$('#countdown').countdown({until: austDay});
Is what I got. I wish to make this static, which I mean by it shows the same countdown in all timezones. So no matter if you change your timezone or your date on your pc, it should not affect the countdown and it should still be e.g 8 hours left.
Maybe this is not possible because Javascript is Client side?
What can I do? I really want it to live countdown and not so you need to refresh. Maybe I can use some help from PHP?
The countdown should be the same for example 4 hours left, it should also display that in new york and asia..

You can use PHP to pass the server time to the client like so.
var time = new Date(<?php echo time()*1000; ?>);

var austDay = new Date("May 18, 2012 00:00:00");
This creates a date object with the date and time shown, in the user's local timezone. To create a UTC date, you can do something like this instead:
var austDay = new Date(Date.UTC(2012, 4, 18));
...where 4 is the zero-based month number (2012 and 18 are the year and day, obviously).
If you need to display the date afterwards, use the "UTC" functions instead of their non-UTC counterparts, for example:
console.log(austDay.toUTCString()) // "Fri, 18 May 2012 00:00:00 GMT"
Another problem is that users could change their clocks. To give them something like "8 hours left" and be absolutely sure, you'd have to compare the server time to the client's time and set the date based on that.
For example, if the server knows that the thing happens at noon tomorrow, and it's 9:00 at night, then the countdown ends in 15 hours. You can tell the client how much time is left until the countdown is ready instead of passing them an absolute time.
var austDay = new Date();
var hoursLeft = <?php echo $something ?>;
austDay.addHours(hoursLeft);
You'd probably want to do it in seconds or smaller instead of hours, I used hours here for simplicity.

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));

Updating Time in Local Storage

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.

Parse date from javascript countdown (jQuery plugin)

I'm trying to parse "Time Left To Buy" from a Groupon clone. Don't worry, everything is legal. The Javascript looks like
var untilDate = new Date(1316206740000);
$("#wlt-DealTimeLeft .timer").countdown({until: untilDate,
layout: "<div class='timerDiv withDay clearfix'><div class='countdownItem days'><p>{dn}</p>{dl}</div><div class='countdownItem'><p>{hn}</p>{hl}</div><div class='countdownSep'>:</div><div class='countdownItem'><p>{mn}</p>{ml}</div><div class='countdownSep'>:</div><div class='countdownItem'><p>{sn}</p>{sl}</div></div>", onTick: function(periods){
$("#wlt-DealTimeLeft").uTimeLeftTick(periods,259080);
}});
I was thinking about the Date value, but it isn't only regular unix timestamp. How can I get the date when the deal ends? It's some kind of jQuery countdown plugin. Thank you for any hints or advices.
javascript Date objects take milliseconds, not seconds, so
var d= new Date(1316206740000);
document.write(d); //outputs Fri Sep 16 17:59:00 UTC-0300 2011

How to add +9 hours on my jQuery script?

How can I add +9 hours on my script below ? I don't prefer to just add 9 hours to the correct time, for example if I want it 13:22:54 to make it 22:22:54 for this to work but on the script.
I create the unix timestamp in a php file doing
$end = mktime(16, 54, 0, 8, 18, 2011);
and the copy it below
Countdown Script
<script type="text/javascript">
var end_date = new Date(<?php echo $end; ?>*1000);
$(document).ready(function() {
$("#time").countdown({
date: end_date,
onComplete: function( event ){
$(this).html("completed");
},
leadingZero: true
});
});
</script>
<p id="time" class="time"></p>
Instead of playing the heroes by trying to do time Math (and even failing badly), you should rely on native methods, available to both PHP and JS:
// gets the time 9 hours from now
// you can give a 2nd parameter to specify when is "now"
$date = strtotime('+9 hours');
and:
// get the time right now
var date = new Date()
// add 9 hours, don't worry about jumping the 24hr boundary, JS resolves correctly.
date.setHours(date.getHours()+9)
Edit:
Since the OP said he wanted to use a TS from DB, here's the relevant code:
$date = strtotime('+9 hours', (int)$db_time);
Note: If $db_time is a formatted string, like "24 April 2011, 4:56 pm", you need to put the following code before the one above:
$db_time = strtotime($db_time);
However, I urge you to check for alternative ways to parse the time.
I'm going to read between the lines here a bit. I assume based on this and previous questions that you want a countdown for some event in the future and you're pulling a timestamp from a database and adding 9 hours to it to get the time of that future event.
Assuming this, you can't use most (any?) of the previous answers because of time zones and the fact that the user's clock might be more or less off. So if you calculate on the server that the event should fire at 5 o'clock and send that info to the user who's 3 time zones away from the server, the countdown will also be 3 hours off (because when it's 5 o'clock where the user is it's either 2 or 8 o'clock where the server is.)
The solution is to calculate the time left until the event and send that information to the browser. This way the countdown will be independent of the user's timezone or their computer's clock. For example if the event is at 5 o'clock and it's now 4 o'clock tell the browser to put 60*60*1=3600 seconds on the timer.
Using part of Christian's answer, do something like this on the server (assuming $db_time contains a Unix timestamp retrieved from the database):
$date = strtotime('+9 hours', (int)$db_time);
$timeUntilEvent = $date - time();
Now $timeUntilEvent contains the amount of seconds until the event. In JavaScript add that number to the timer:
var end_date = new Date();
end_date.setTime( end_date.getTime() + <?php echo $timeUntilEvent; ?> * 1000 );
Now the timer will fire at the correct time regardless of what time the user's clock is set to.
var end_date = new Date((<?php echo $end; ?>+32400)*1000);
end_date = end_date + ((3600*1000)*9);
mktime returns seconds, so you simply add the desired amount of seconds
using the end_date created with php, add this line:
end_date+=9*60*60
Call this before your countdown:
end_date = end_date.setTime((end_date + (9 * 3600)) * 1000).toGMTString();
EDIT: I removed the get_time() and the "* 1000" as end_date is already a UNIX timestamp.
EDIT2: Apparently, timestamps in js are in milliseconds so we also have to multiply the PHP timestamp (which is in seconds).

PHP date issues with daylight saving

I've got a very strange bug cropping up in some PHP code I've got. The page is managing student enrolments in courses. On the page is a table of the student's courses, and each row has a number of dates: when they enrolled, when they completed, when they passed the assessment and when they picked up their certificate.
The table data is generated by PHP (drawing the data from the DB), and Javascript actually renders the table. The output from PHP is JS code which looks something like this:
var e = new Enrolment();
e.contactId = 5801;
e.enrolId = 14834;
e.courseId = 3;
e.dateEnrolled = new Date(1219672800000);
e.dateCompleted = new Date(-1000); // magic value meaning they haven't completed.
e.resultDate = new Date(1223647200000);
e.certDate = new Date(1223560800000);
e.result = 95;
e.passed = true;
enrolments[14834] = e;
In the database, all the date fields are stored as DATE (not DATETIME) fields.
The bug is that the dates are being displayed as one day off. I would suspect that this has a lot to do with the server being in an area which has daylight saving, whereas here there isn't any (meaning the server time is one hour off). This explains a lot, especially how the data preparation and rendering is being done in two different timezones. That is: the server is saying to the client that the person completed at midnight on the 15th August, and the client is interpreting that as 11pm on the 14th and therefore displaying 14th August.
But here's the confusing part: it's only doing that for the resultDate and certDate fields! I've copied the data to my local server and have found that the production server is actually sending a different timestamp (one which is off by 1 hour) just for those two fields, whereas the dateEnrolled field is the same.
Here's the output using the exact same code and data from the database:
// local server (timezone GMT+1000)
e.dateEnrolled = new Date(1219672800000); // 26 Aug 2008 00:00 +10:00
e.dateCompleted = new Date(-1000);
e.resultDate = new Date(1223647200000); // 11 Oct 2008 00:00 +10:00
e.certDate = new Date(1223560800000); // 10 Oct 2008 00:00 +10:00
// production server (timezone GMT+1100)
e.dateEnrolled = new Date(1219672800000); // 26 Aug 2008 00:00 +10:00
e.dateCompleted = new Date(-1000);
e.resultDate = new Date(1223643600000); // 10 Oct 2008 23:00 +10:00 **
e.certDate = new Date(1223557200000); // 09 Oct 2008 23:00 +10:00 **
I can understand if this was a problem with Daylight Saving not being accounted for, but notice how the dateEnrolled is the same?
The PHP code which converts the MySQL date to a unix timestamp is this:
list ($year, $month, $day) = explode ('-', $mysqlDT);
$timestamp = mktime (0,0,0, $month, $day, $year);
Any ideas about how to fix this?
Thats because you use mktime which is locale specific. That is it will convert it to the number of seconds from 00:00:00 1970-1-1 GMT, and that is offset by 1 hour with one timezone.
You should also remember that the javascript does use the same timezone as the browser, not the web page.
e.resultDate = new Date(year, month - 1, day);
This will make sure the date is the same for every viewer from every timezone.
Or you can use gmmktime and use the UTC methods in Date.
Ok, I just figured out why it's mucking up one date but not the other. Daylight savings wasn't in effect in August. facepalm
always store dates/datetimes in GMT/UTC
take a good look at the query that retrieves these values, anything different about the ones being adjusted?
if not, are they all timestamp or date or datetime?
It is mosly likely to be day light saving issue.
The reason why it doing it only for resultDate and certDate is that dateEnrolled is in August, daylight saving normally begins/ends in late September or early October.
Set the date.timezone ini setting to your app's timezone, using apache.conf, .htaccess or ini_set().

Categories