Trying to use jQuery Countdown with UNIX timestamp from php - php

As the title says I'm facing a problem displaying the right left time to an end date.
I'm using this jquery plugin: http://keith-wood.name/countdown.html
Let's assume that our timestamp is generated by a PHP script like this: $end_date = strtotime($row4['end']); // 2012-05-09 06:00:00 becomes 1336536000
I use this ($i is used inside a loop):
$('.count-<?php echo $i; ?>').countdown({until: new Date(<?php echo $end_date; ?> * 1000), layout: '{dn} days {hnn} hrs {mnn} min {snn} sec', compact: true});
Right now it's 06:21 AM here. Instead of the expected 1 day left result I get "1 days 17 hrs 04 min 21 sec".
What am I missing here?

I have been using the API for quite a while now, but I cann't seem to figure out what's up with your code. Perhaps (but just perhaps) you're using the untill property wrong.
My code that I usually use:
$(function(){
var countdown = $('#countdown'),
ts = new Date(<?php echo $date_to * 1000; ?>),
finished = true;
if((new Date()) > ts)
{
finished = false;
}
$('#cool-countdown').countdown({
timestamp : ts,
callback : function(days, hours, minutes, seconds)
{
var message = "";
message += days + " days, ";
message += hours + " hours, ";
message += minutes + " minutes, ";
message += seconds + " seconds ";
message = (finished ? "Countdown finished" : "left untill the New Year");
countdown.html(message);
}
});
});
Obviously you should extend this to feature singular.

Related

How to make a countup timer instead of a countdown timer? (PHP, JQUERY AJAX)

I made a countdowntimer in PHP and jQuery AJAX who is showing every second the variable named $timeleft.
timer.js
$(function()
{
var timertext = $("[timer]");
setInterval(function()
{
$.post("timer.php", {type : "timerupdate"}, function(data)
{
timertext.html("Time left: " + data + " seconds")
});
}, 1000);
});
timer.php
date_default_timezone_set("Europe/Amsterdam");
$timecountdownend = strtotime("2020-05-18 14:30:00");
$timecountdownstart = strtotime("now");
$startdatetime = "2020-05-18 14:07:00"; //variable for starting datetime
if(date('Y-m-d H:i:s') >= $startdatetime){
$timeleft = $timecountdownend - $timecountdownstart;
if(isset($_POST["type"]) === true && $_POST["type"] == "timerupdate")
{
echo ($timeleft);
}
}
Explained: a timer that starts when it's a specific time ($startdatetime) and counting the seconds till the $timecountdownend time. It's working fine, but I actually want to count up the second instead of counting down. So that it start counting with 1 second if $startdatetime has reached and every second is counting up till the $timecountdownend has reached. How can I do this with strtotime? I've tried many things like $timeleft = $timecountdownend - strtotime(date('Y-m-d H:i:s')); but it didn't work.
Many thanks in advance.
First if You have timeleft its Your counter : -2820
You can simply multiple it by (-1) : -2820 * (-1) = 2820
date_default_timezone_set("Europe/Amsterdam");
$timecountdownend = strtotime("2020-05-18 14:30:00");
$timecountdownstart = strtotime("now");
$startdatetime = "2020-05-18 14:07:00"; //variable for starting datetime
$timeleft = $timecountdownend - $timecountdownstart;
echo ($timeleft);
echo(PHP_EOL);
echo ($timeleft*(-1));
echo(PHP_EOL);
echo( date('Y-m-d h:i:sa',strtotime($startdatetime)+$timeleft*(-1)));
http://sandbox.onlinephpfunctions.com/code/792ec42255d85a45c377b6e8d34cbde143430824

How to get first time from server by php and put in JavaScript

How can I get first time from server by php?
I've tested this code but it does not work. It gets the time but it is not counting? What's the problem?
<script type="text/javascript">
function GetClock(){
d = new Date(<?php echo date("y, n, j, G, i, s");?>);
nhour = d.getHours();
nmin = d.getMinutes();
nsec = d.getSeconds();
if(nhour == 0) {
ap = " AM";nhour = 12;
} else if(nhour <= 11) {
ap = " AM";
} else if(nhour == 12) {
ap = " PM";
} else if(nhour >= 13) {
ap = " PM";nhour -= 12;
}
if(nmin <= 9) {
nmin = "0" +nmin;
} if(nsec <= 9) {
nsec = "0" +nsec;
}
document.getElementById('clockbox').innerHTML=""+nhour+":"+nmin+":"+nsec+ap+"";
setTimeout("GetClock()", 1000);
}
window.onload=GetClock;
</script>
Explanation
The question is why are you using PHP to write a datetime into the Date object in JS?
The PHP will only write out the time at the point at which the page renders, it will never change again.
You are then setting your counter based on a Javascript setTimeout every 1 second, expecting the clock to increment in seconds, but it is always based on the same original time (the page render time) and is always incremented by 1 second.
For example. The page loads at 12:00:00 on June 3 2013. Your code looks like this:
d = new Date(13, 6, 3, 12, 0, 0);
at the time the pages loads (if you view source)
1 second later the setTimeout fires and renders the clock at 12:0:01, based on the starting time in the date object.
But your starting time never changes, so each further second that passes and triggers setTimeout will base the calculations on 12:00:00 not the current time
TLDR; and answer
Remove the PHP!
d = new Date();
Alternatively, if you absolutely have to use server time. You would need to initialise the date object as you have done, but then store a count of how many seconds have passed and calculate the difference

Clock widgets in PHP

I need to show system date in my web site through wordpress in PHP.
it shows system time one time but not updating as days gone passed.
I need to change it according to my system date
You can't show your system time using PHP. If you want to show your system time you just need to use javascript.
try this,
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
if (minutes < 10)
minutes = "0" + minutes
document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>")
Update:
If you want to show everything, please try this.
<script type="text/javascript">
document.write(new Date());
</script>

Client time settings broke readable date in javascript

What i'm trying to do is show date in more readable format like 3 seconds ago, 1 hours ago, yesterday, June 12 and etc.
What i did is , first calculate the timestamp for comment's date.. Then send it to client with ajax, then create two date instance on javascript one for is comment's date and other one is current date.. After that I just find differences between to date item then write on the screen with fancy words..
Everything works fine on localhost, even server.. But sometimes if client's pc date is earlier from the server date (independent from time zone)..
Let say server time is today 13.30 pm and client time is today 13.00 , it's failing with this scenario because current time is being comment's post time.. Difference will be negative value..
I'm creating date object for comment in php like this;
date("Y-m-d G:i:s")
Then write it to mysql db..
After that when i select comments i convert it to timestamp to push it on client side with ;
$comment['timestamp'] = strtotime($row['creationDate']);
And then in javascript, I make calculation for human readable date format ;
DateObject.getFormatted = function(unixtime){
d = new Date(unixtime*1000);
now = new Date();
var diff = (now.getTime()/1000- unixtime) ;
var result = "";
var MIN = 60,
HOUR = 3600,
DAY = 86400;
if(diff < 2)
result ="just now";
else if(diff < MIN)
result = Math.floor(diff) + " seconds ago";
else if(diff < HOUR)
result = Math.floor(diff/60) + " minutes ago";
else if(diff < DAY)
result = Math.floor(diff/3600) + " hours ago";
else if(diff < DAY*3)
{
var days = diff/DAY;
if(days < 2)
result = "yesterday";
else
result = Math.floor(days) + " days ago";
}
else if(now.getFullYear() == d.getFullYear())
{
formattedTime = this.getTime(d);
result = this.getSameYear(d) + " at " + formattedTime;
}
else
{
formattedDate = this.getDate(d);
formattedTime = this.getTime(d);
result = formattedDate + " at " + formattedTime;
}
return result;
};
So if clients date is earlier then the comment's date diff value is being negative, so the first case would be true
if(diff < 2)
result ="just now";
It's going behing as time difference between client and comment's date .. In my case 10 minutes.. If I set my computer time 10 minutes later it's working nice..
So how can i fix it in a better way?
Thank you.
May be better send from server to client difference between comment date and current date?(instead of creation two javascript date instances)
A third date so you can calculate the difference between server and client and use it as an offset?

Calculating the time difference in an PHP/MySQL/JavaScript system

I was wondering what the best way is to calculate the difference in time from now to a certain point, let's say the countdown time.
I have an auction that has a closetime at a certain point, this time is stored in a MySQL record in the format " DATETIME 00-00-000 00:00:00 ". This record is called closetime.
Now on my website I have JavaScript code that gets this time via a PHP file. The JavaScript loops every second using setInterval 1000. The PHP file gets the closetime from the db, and sends it back in this format
strtotime($result['closetime']);
And I get the time of the request, I want to use the server time, and not the time in JavaScript, because the clock of the user can be off.
strtotime(date("H:i:s", $_SERVER['REQUEST_TIME']))
I send back these two timestamps and calculate the time difference between them in JavaScript. I use this function to do it, the values send back from PHP I call currentTime and closeTime, I think this should be clear.
function auctionDelayTime(currentTime,closeTime){
totaldelay = closeTime - currentTime;
if(totaldelay <= 0){
return 'ended';
}else{
if( days=parseInt((Math.floor(totaldelay/86400))) )
totaldelay = totaldelay % 86400;
if( hours=parseInt((Math.floor(totaldelay/3600))) )
totaldelay = totaldelay % 3600;
if( minutes=parseInt((Math.floor(totaldelay/60))) )
totaldelay = totaldelay % 60;
if( seconds=parseInt((Math.floor(totaldelay/1))) )
totaldelay = totaldelay % 1;
return hours+':'+formatTimes(minutes)+':'+formatTimes(seconds);
}
}
function formatTimes(value){
return value < 10 ? '0'+value : value;
}
I think this is an awful lot of code do something so simple. Does anyone have a better solution or maybe more 'beautiful' code.
Enjoy!
There is a jquery Countdown Plugin that supports server sync through AJAX:
From the docs:
Synchronise the client's time with
that of the server by providing a
function that returns the current
server date and time. This date and
time should take into account the
server's timezone and any difference
between that time and the client's is
applied to the countdown when it is
started or changed.
The following example uses a PHP
program on the server to return the
current server time in a format that
can be used directly by the JavaScript
callback. You should make sure that
your server call is synchronous.
$(selector).countdown({
until:liftoffTime, serverSync: serverTime});
function serverTime() {
var time = null;
$.ajax({url: 'http://myserver.com/serverTime.php',
async: false, dataType: 'text',
success: function(text) {
time = new Date(text);
}, error: function(http, message, exc) {
time = new Date();
}});
return time;
}
serverTime.php:
<?php
$now = new DateTime();
echo $now->format("M j, Y H:i:s O")."\n";
?>
Use Date object.
var d = new Date(difference_in_milliseconds);
var seconds = d.getSeconds();
var minutes = d.getMinutes();
var hours = d.getHours() - 1; //See note
Note: Strangely, hours value is bigger by one than I would expect for reason I don't understand. It looks like "midnight Jan 1, 1970" was at 1 AM :-)
UPDATE: The difference of 1 is due to the offset of my timezone (GMT +1).
Slight change that will solve this:
var d = new Date();
var offset = d.getTimezoneOffset() * 60000;
var d = new Date(difference_in_milliseconds + offset);
var seconds = d.getSeconds();
var minutes = d.getMinutes();
var hours = d.getHours();
This JavaScript library is easy to use and will likely serve you well.
Why not have the php page give you the difference?
$sql = "SELECT UNIX_TIMESTAMP(NOW()) as currentTime, UNIX_TIMESTAMP(closeTime) as closeTime FROM yourTable WHERE yourRecordId = '123'";
$query = mysql_query($sql);
$result = mysql_fetch_assoc($query);
echo timeRemaining($result['currentTime'], $result['closeTime']);
function timeRemaining($start, $end) {
$dateDiff = $end - $start;
if ($dateDiff <= 0) { return 'Ended'; }
$fullDays = floor($dateDiff/(60*60*24));
$fullHours = floor(($dateDiff-($fullDays*60*60*24))/(60*60));
$fullMinutes = floor(($dateDiff-($fullDays*60*60*24)-($fullHours*60*60))/60);
return "Ending in $fullDays days, $fullHours hours and $fullMinutes minutes.";
}
Do you really have to get the time through AJAX every 1000 ms?
(i suppose that you're hoping for closetime changes? ...)
But if you really must do it this way, i'd suggest getting the time difference directly in MySQL for code simplicity.
$sql = "SELECT TIMEDIFF(NOW(), `CreateTime`) from `Table` WHERE `id`=1;"

Categories