I am building a JavaScript countdown, that needs to rely on the server time but I cant manage to transfers the php time to javascript in a crossbrowser manner. This workes well in all Mordern browsers, but brakes in older ones (Date not defined). If I go with date("Y-m-d H:i:s) instead of date("Y-m-d\TH:i:s\Z) it works better but not in IE10
<?php
switch ($day) {
case 'Sat':
$start = "10";
$stop = "16";
break;
case 'Sun':
$start = "11";
$stop = "16";
break;
default:
$start = "10";
$stop = "19";
break;
}
?>
<script>
jQuery(function(){
var open = new Date("<?php echo date("Y-m-d\TH:i:s\Z",strtotime("today {$start}:00:00")); ?>");
var end = new Date("<?php echo date("Y-m-d\TH:i:s\Z",strtotime("today {$stop}:00:00")); ?>");
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var start = new Date("<?php echo date("Y-m-d\TH:i:s\Z"); ?>") ;
});
</script>
The only format officially recognized by ECMAScript/JavaScript is ISO 8601 Extended:
The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ
But, this is new with ECMAScript 5. Prior versions left support up to each vendor to decide.
You could try using timestamps rather than strings.
var open = new Date(<?php echo strtotime("today {$start}:00:00") * 1000; ?>);
// ...
var start = new Date(<?php echo time() * 1000; ?>);
Both JavaScript and PHP use UTC-based timestamps, just with the difference of seconds (PHP) vs. milliseconds (JS).
Firstly, Javascript date() is accept the milliseconds, or dateString.
The milliseconds similar to php time().
The dateString should be used this format: October 13, 2012 11:13:00
By you case, I suggest using strtotime() or time() to return the timestamp, but you need * 1000 before pass to javascript.
Ref: W3schools - Date Object Reference
Related
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
trying to make a simple countdown timer in PHP based on some input from a database which will tweak the end time slightly (with a constant base). However it seems to keep throwing up really strange numbers in the countdowns. I pretty much guarantee my math is wrong somewhere.
PHP
$timeUntil = 10; // for tweaking time remaining (days), this will be dynamic in actual program but will always be an integer
$timeStamp = 1445438099; // timestamp of roughly 2 months in the future
$zUnixDays = $timeUntil * 86400; // converting integer (days) into seconds
$zFinalTime = $timeStamp - $zUnixDays; //tweaking the constant time with the variable time
$remaining = $zFinalTime - time(); // seconds remaining from the future time til now
$seconds_remaining = $remaining%60;
$minutes_remaining = floor(($remaining%3600)/60);
$hours_remaining = floor(($remaining%86400)/3600);
$days_remaining = floor(($remaining%2592000)/86400);
$zTimeCombined = array($days_remaining, $hours_remaining, $minutes_remaining, $seconds_remaining);
echo json_encode($zTimeCombined);
JS
var result = JSON.parse(results);
var zDays = result[0];
var zHours = result[1];
var zMinutes = result[2];
var zSeconds = result[3];
this should return around 50 days remaining (2 months - 10 days.. very rough) but instead returns 21 days. Any ideas anyone?
Use DateTime instead, it's much easier:
$future = new DateTime();
$future->setTimestamp(1445438099); // passing in to constructor directly is wonky
$start = $future->sub(new DateInterval('P10D'));
$diff = $start->diff(new DateTime());
$interval = $diff->format('%y:%m:%d:%h:%i:%s');
// 0:1:20:23:29:45
list($year, $month, $day, $hour, $minute, $second) = explode(':', $interval);
<?php
$daysToFuture = 10;
// 10 Days in Future
$futureTs = mktime(0,0,0,date("n"),date("j")+$daysToFuture,date("Y"));
// remaining till now ...
$remaining = $futureTs-time();
// in Days
$days_remaining = date("d",$remaining);
echo "<pre>"; print_r($days_remaining); echo "</pre>";
// in hours
$hours_remaining = date("H",$remaining);
echo "<pre>"; print_r($hours_remaining); echo "</pre>";
// in minutes
$minutes_remaining = date("i",$remaining);
echo "<pre>"; print_r($minutes_remaining); echo "</pre>";
// in seconds
$seconds_remaining = date("s",$remaining);
echo "<pre>"; print_r($seconds_remaining); echo "</pre>";
// Array
$zTimeCombined = array($days_remaining, $hours_remaining, $minutes_remaining, $seconds_remaining);
echo "<pre>"; print_r($zTimeCombined); echo "</pre>";
I recommend you to use the DateTime and DateInterval objects
$dateTime = new DateTime();
$dateTime->setTimestamp(1445438099);
$timeInTheFuture = $dateTime->modify('-10 days');
$dateInterval = $timeInTheFuture->diff(new DateTime());
echo json_encode(explode(' ', $dateInterval->format('%d %h %i %s')));
I am trying to show ticker clock for different timezone. When I looked around the web, it looks like it takes number for the offset(for example +5.5 hours) in javascript. But the way we are getting the gmtformat is +05:30 in php which I am trying to feed in to the javascript function. Is there any function that I can use to convert?
/*CLOCK CODE IN JAVASCRIPT*/
function startclock(field, timediff, newOrRepeat)
{
var clockAction=newOrRepeat;
if (timediff=="") {$(field).html("-------");return false;}
/****THERE ARE MORE STUFF IN BETWEEN AND AFTER WHICH IS NOT RELEVANT TO OFFSET****/
var secondsDiff=0;
var secondsTimeZone = 0;
//calculate the difference in time set by both the timezone as well as the DST
secondsTimeZone = parseInt(timediff);
if ($("input[name='daylight']:checked").val()=="on" && $(field).siblings("#isDaylight").val()=="no")
secondsDiff=secondsTimeZone + 3600;
else if ($("input[name='daylight']:checked").val()=="off" && $(field).siblings("#isDaylight").val()=="yes")
secondsDiff=secondsTimeZone - 3600;
else
secondsDiff = secondsTimeZone;
var thetime=new Date();
thetime.setUTCSeconds(parseInt(thetime.getUTCSeconds())+parseInt(secondsDiff));
var nhours=thetime.getUTCHours();
var nmins=thetime.getUTCMinutes();
var nsecn=thetime.getUTCSeconds();
}
I am getting getting gmt format straight from php which i am passing to this function.
function convert_time($time){
$parts = explode(':', $time);
return $parts[0] + number_format($parts[1]/60, 2);
}
How can I get the time of the client side?
When I use date() it returns server's time.
Here's a "PHP" solution:
echo '<script type="text/javascript">
var x = new Date()
document.write(x)
</script>';
As mentioned by everyone PHP only displays server side time.
For client side, you would need Javascript, something like the following should do the trick.
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
if (minutes < 10) {
minutes = "0" + minutes;
}
document.write("<b>" + hours + ":" + minutes + " " + "</b>");
And if you want the AM/PM suffix, something like the following should work:
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>");
Here is a list of additional JavaScript Date and Time functions you could mess around with.
You could possibly use Geolocation by IP Address to work out which country the user is in, and then use that.
But using Javascript or letting the user choose a Timezone will probably be better.
As PHP runs on the server-side, you cannot access the client-side time from PHP : PHP doesn't know much about the browser -- and you can have PHP scripts that run without being called from a browser.
But you could get it from Javascript (which is executed on the client-side), and, then, pass it to PHP via an Ajax request, for example.
And here are a couple of questions+answers that might help you getting started :
Automatically detect user’s current local time with JavaScript or PHP
How can I determine a web user’s time zone?
PHP is server side only as far as i know.
You maybe want to use JavaScript.
As other's have mentioned, you can use Geo Location Services based on the IP Address.
I found it to be off by about 18 seconds due to IP location accuracy, by using a $responseTime offset it helped me narrow it down to 2 second accuracy in the Viewers Location.
<?php;
echo deviceTime('D, M d Y h:i:s a');
function deviceTime($dateFormatString)
{
$responseTime = 21;
$ip = (isset($_SERVER["HTTP_CF_CONNECTING_IP"])?$_SERVER["HTTP_CF_CONNECTING_IP"]:$_SERVER['REMOTE_ADDR']);
$ch = file_get_contents('https://ipapi.co/'.$viewersIP.'/json/');
$ipParts = json_decode($ch,true);
$timezone = $ipParts['timezone'];
$date = new DateTime(date('m/d/Y h:i:s a', time()+$responseTime));
$date->setTimezone(new DateTimeZone($timezone));
return $date->format($dateFormatString);
}
?>
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;"