Javascript .getHours() returns strange result - php

I'm converting a PHP timestamp into a human readable form in javascript:
<script type="text/javascript">
var timeleft = new Date( <?php echo $lefttime; ?> * 1000 );
var hours = timeleft.getHours();
var minutes = timeleft.getMinutes();
var seconds = timeleft.getSeconds();
var countdown = function() {
console.log( "You have " + hours + ":" + minutes + ":" + seconds + " seconds left" );
</script>
The minutes and seconds work but I'm getting strange results for the hours. For example:
Timestamp: 1976
Function returns: 19:32:56
Any ideas why I'm getting "19" from .getHours() ?

I'm going to hazard a guess that you're in Eastern Time. What you are seeing is $lefttime seconds after the epoch, which in the case of EST is 7PM.
To fix it, just use basic math:
var timeleft = <?php echo $lefttime; ?>;
var hours = Math.floor(timeleft/3600);
var minutes = Math.floor(timeleft/60)%60;
var seconds = timeleft%60;

Related

Error date NaN in firefox and IE

Hello I need to spend a given XML through javascript to subtract the current date and time date.
What makes this code is to show the remaining time of a song streaming in minutes and seconds
And then with javascript parsing date and I transform in milliseconds and the current date will also rest in ms.
In Chrome date shows me perfectly, but in Mozilla and IE NaN console shows me and gives error.
I do not understand is that if I have parsed the date because it only works in Chrome. There must be a mistake.
PHP (I draw the start date of a song)
<?php
$xml = # simplexml_load_file('http://www.example.com');
foreach ($xml as $track){
$startTime = $track->starttime;
$songDuration = $track->playduration;
}
?>
JAVASCRIPT:
var spend javascript
var tiempoComienzo= "<?php echo $startTime ?>";
var cancionDuracion="<?php echo $songDuration ?>";
//parse delivered date from php
var d = new Date(Date.parse(tiempoComienzo));
//PHP get the date in milliseconds
var resultPHPms = d.getTime();
//get the current date
var f = new Date();
//step the current date to milliseconds
var resultJSms = f.getTime();
//adding the date of the song to the length of the song
var inicioMasCancion=parseInt(cancionDuracion) + parseInt(resultPHPms);
//It is the challenge to the current date
var TiempoRestante=inicioMasCancion-parseInt(resultJSms);
//pass the result to seconds
seconds=(TiempoRestante/1000)
var container = document.getElementById('time');
var seconds = parseInt(seconds+7);
//step seconds to minutes and seconds
var minutes = parseInt( seconds / 60 ) % 60;
var seconds = seconds % 60;
var contadorDeTiempo=(minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
countdown(seconds);
function countdown:
<script>
var timer;
function countdown(seconds) {
seconds--;
if(seconds >= -1) {
container.innerHTML =contadorDeTiempo;
}
}
timer = setInterval(countdown, 1000);
</script>
HTML:
<span id='time'></span>
In chrome it is perfectly displayed and works perfect. But in Mozilla and IE console NaN it is shown, specifically in this line:
var d = new Date(Date.parse(tiempoComienzo));
How I could solve? The resulting XML date is as follows:
2015-12-20 12:45:33.17
thanks very much for your help

jQuery and PHP Countdown timer from formatted variable

I need to build a countdown timer in jquery that replaces the html in a span tag from a php variable that's formatted to XX Days XX:XX:XX. It should load the variable on page load and then when the jquery script loads it starts the countdown but keeping the same format (XX Days XX:XX:XX) and eventually displays "Expired" and stops the countdown.
I have a jsFiddle started (http://jsfiddle.net/2SDdh/1/) but it shows the formatted time and then loads a 10 sec countdown and eventually shows "Expired". Anyone know how to get the formatting correct?
My HTML output via PHP
<span class="exp">10 Days 10:10:10</span>
My jQuery
$(function(){
var count = 10;
countdown = setInterval(function(){
if (count > 0) {
count--;
$(".exp").html(count);
} else {
$(".exp").html('Expired');
}
}, 1000);
});
try this
html:
<span class="days">10</span> Days <br />
<span class="exp">23:59:59</span>​
javascript :
$(function(){
var days = 10;
var count = 86399;
var count2 = 0;
var hour = 0;
var min = 0;
var sec = 0;
countdown = setInterval(function() {
if (days != 0 || count != 0) {
if (count == 0) {
days--;
count = 86399;
} else {
count--;
}
count2 = count;
hour = Math.floor(count2 / 3600);
count2 = count2 % 3600;
min = Math.floor(count2 / 60);
count2 = count2 % 60;
sec = count2;
$(".exp").html(hour + ":" + min + ":" + sec);
$(".days").html(days);
} else {
$(".exp").html('Expired');
}
}, 1000);
});​
Cheers!
Instead of rolling your own countdown timer, why not use one that already exists?. KK Countdown works well for me.

create an notification/alert at an specific time

I have created a timer to be used as a reference on a alert when the timer reaches exactly 5:00 pm/ 17:00. Do you have any ideas how could I do that? Do I check the time once in a while?
Here's how I create my timer.
<script language="JavaScript">
var tick;
function stop() {
clearTimeout(tick);
}
function usnotime() {
var datetoday = document.getElementById("datenow")
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
datetoday.val("" + month + "/" + day + "/" + year + "");
var txt = document.getElementById("timeticker")
var ut = new Date();
var h, m, s;
var time = " ";
h = ut.getHours();
m = ut.getMinutes();
s = ut.getSeconds();
if (s <= 9) s = "0" + s;
if (m <= 9) m = "0" + m;
if (h <= 9) h = "0" + h;
time += h + ":" + m + ":" + s;
txt.innerHTML = time;
tick = setTimeout("usnotime()", 1000);
}
//--> document.rclock.rtime.value=time; tick=setTimeout("usnotime()",1000); } //-->
</script>
<tr>
<td class="tdlabel">Current Time:</td>
<td>
<div id="timeticker" name="rtime" size="22"></div>
</td>
</tr>
And it seems that my timer is not displaying. Any ideas??
You have a mistake, you mixed javascript and jquery.
datetoday.val("" + month + "/" + day + "/" + year + "");
Should be (assuming datetoday is a textfield. If div use innerHTML instead of value)
datetoday.value="" + month + "/" + day + "/" + year + "";
and add just before the closing script tag
window.onload=function(){
usnotime();
}
Not sure if this is the exact answer; it might help posting a bit more code.
I don't see how you're starting the method. You might need to add a button-execute / page-load call of usnotime().
Do you have real objects for all of those variables? (I.e. timeticker, datenow).
Check your JavaScript error log in the browser. It's a bit hard without more code for me to see what's wrong, so either include more, or use the debugger.
Using the setTimeout() u can do , Refer this it may be useful for you
This may help you....
<html>
<head>
<title>(Type a title for your page here)</title>
<script type="text/javascript">
function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}
function display_ct() {
var strcount
var x
var x1
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds= currentTime.getSeconds()
x=month + "/" + day + "/" + year
if (minutes < 10){
minutes = "0" + minutes
}
x=x+" "+hours + ":" + minutes +":"+seconds+ " "
x1=hours + ":" + minutes + ":"+seconds+" "
if(hours > 11){
x=x+"PM"
x1=x1+"PM"
if(x1=="5:30:0 PM"){alert(x1);}
} else {
x=x+"AM"
x1=x1+"AM"
if(x1=="8:16:0 AM"){alert(x1);}
}
document.getElementById('ct').innerHTML = x;
tt=display_c();
}
</script>
</head>
<body onload=display_ct();>
<span id='ct' ></span>
</body>
</html>

Time count down like www.bidhere.com

Can anybody please suggest to me how I can create a time countdown like www.bidhere.com.
what are the techniques used on that. e.g jQuery or cronjob ?
Thanks.
You can use javascript to achieve that affect
Markup
<body>
<div id="countdown"></div>
</body>
Javascript
function countdown(remain) {
var countdown = document.getElementById("countdown"),
timer = setInterval( function () {
countdown.innerHTML = (remain%60 < 10 ? "0": "") + remain %60;
if (--remain < 0 ) { clearInterval(timer); }
},1000);
}
countdown(20);
<span class="countdown" rel="30">0:30</span><br/>
<span class="countdown" rel="60">1:00</span><br/>
<span class="countdown" rel="1800">30:00</span><br/>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
// Initialization
$(document).ready(function(){
// Replace <span class="countdown"> rel content with the expiry epoch time
var date = new Date(); // This gives you an epoch date in milliseconds
$('span.countdown').each(function(){
// We do rel*1000 to convert to milliseconds, cause rel is in seconds
$(this).attr('rel', date.getTime()+parseInt($(this).attr('rel'))*1000);
});
// Set an interval so updateCountdown() is called every second
setInterval('updateCountdown()', 1000);
});
// Update, called every second
function updateCountdown() {
var date = new Date(); // This gives you an epoch date in milliseconds
// For each <span class="countdown">
$('span.countdown').each(function(){
// Get time left in milliseconds
var timeLeft = parseInt($(this).attr('rel')) - date.getTime();
// Convert from milliseconds to seconds
timeLeft = Math.round(timeLeft/1000);
// Set to 0 if negative
if (timeLeft < 0) timeLeft = 0;
// Extract minutes and seconds for display
var secs = timeLeft % 60;
var mins = (timeLeft-secs)/60;
// Change <span> content
$(this).text(mins+':'+(secs<10?'0':'')+secs);
});
}
</script>

Countdown Timer

My project in php
I want to create a countdown timer for asking question in limited timeframe like LMS
here i have use the javascript countdown timer but when refresh the page javascript timer are reset.
You could store the start time in a php session. Then everytime you load a page you can continue the countdown timer with javascript, e.g.
<?php
//on every page
session_start();
//when you start
$_SESSION['start_time'] = time();
Then on every page:
<script type="text/javascript">
var startTime = <?php echo $_SESSION['start_time']; ?>;
//calculate remaining time
</script>
You will need to watch for when the timezones are different, or when the client's clock is wrong. Maybe instead you could calculate the remaining time in seconds and print that into javascript on each page, but then you could have innacuracy over high latency connections etc.
Try something like:
<?php
session_start();
//to reset the saved countdown
if (!empty($_REQUEST['resetCountdown']))
{
unset($_SESSION['startTime']);
}
if (empty($_SESSION['startTime']))
{
$_SESSION['startTime'] = time();
}
//In seconds
$startTime = time() - $_SESSION['startTime'];
?>
<script type="text/javascript">
var countdown = 60; //in seconds
var startTime = <?php echo $startTime; ?>;
startCountdown(startTime, countdown);
function startCountdown(startFrom, duration)
{
//countdown implementation
}
</script>
You could also store the timer in a session variable in PHP so that when the page is refreshed the time is still preserved.
try this
<script>
// Set the date we're counting down to
var countDownDate = new Date("Aug 1, 2017 12:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
and also put this under body tag.
<p id="demo"></p>

Categories