function timeClock()
{
setTimeout("timeClock()", 1000);
now = new Date();
alert(now);
f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
return f_date;
}
<span class="foo"><script type="text/javascript">document.write(timeClock());</script></span>
alert(now); gives me the value every second but it is not updated in the html. How can I update the time on the html without refresh the page?
There are a number of mistakes in your code. Without the use of var infront of your variable declarations, you leak them into the global scope.
Also, the use of document.write is discouraged.
Here's how I would do it:
JavaScript:
function updateClock() {
var now = new Date(), // current date
months = ['January', 'February', '...']; // you get the idea
time = now.getHours() + ':' + now.getMinutes(), // again, you get the idea
// a cleaner way than string concatenation
date = [now.getDate(),
months[now.getMonth()],
now.getFullYear()].join(' ');
// set the content of the element with the ID time to the formatted string
document.getElementById('time').innerHTML = [date, time].join(' / ');
// call this function again in 1000ms
setTimeout(updateClock, 1000);
}
updateClock(); // initial call
HTML:
<div id="time"> </div>
setInterval(expression, timeout);
The function setTimeout is intended for a single timeout, so using setInterval would be a more appropriate option. SetInterval will run regularly without the additional lines that Ivo's answer has.
I would rewrite Ivo's answer as follows:
JavaScript:
function updateClock() {
// Ivo's content to create the date.
document.getElementById('time').innerHTML = [date, time].join(' / ')
}
setInterval(updateClock, 1000);
Try it out yourself! https://jsfiddle.net/avotre/rtuna4x7/2/
x = document.getElementsByTagName('SPAN').item(0);
x.innerHTML = f_date;
try putting this code block instead of return statement, i haven't test it but it will probably work
There may be something in timeago jQuery plugin you can hook into, but I haven't honestly tried...
http://timeago.yarp.com/
$('span.foo').html(f_date);
place this inside your timeclock() function
untested
function timeClock()
{
setTimeout("timeClock()", 1000);
now = new Date();
alert(now);
f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
$('span.foo').html(f_date);
}
I'd use setInterval rather than setTimeout:
https://developer.mozilla.org/en/DOM/window.setInterval
I think your setTmeout function has the wrong variables, the first one should be a function not a string, that confused me for a bit. Basically you need to write to the span tag when you run the function.
I created a jQuery version in a fiddle to demonstrate what I mean. Didn't have your strMonth function but you get the idea. I also changed the alert to console.log but you can remove that line.
http://jsfiddle.net/5JWEV/
Straigt Javascript time format / update
1: create month converter func
2: create time func
3: create update func
4: create outPut func
// month converter from index / 0-11 values
function covertMonth(num){
let months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
// look into index with num 0-11
let computedRes = months[num];
return computedRes;
}
// time func
function Time(){
// important to get new instant of the Date referrance
let date = new Date();
this.time = date.toLocaleTimeString();
this.year = date.getUTCFullYear();
this.day = date.getUTCDate();
this.month = date.getUTCMonth();
this.currentTime = date.toLocaleTimeString() + ' ' + covertMonth(this.month) + ' ' + this.day + ' ' + this.year;
return this.currentTime;
}
function timeOutPut(){
let where = document.getElementById('some-id');
where.textContent = Time(); // 1:21:39 AM Dec 17 2017
}
// run every 5secs
setInterval(timeOutPut, 5000);
I used #soloproper setInterval concept #Ivo Wetzel overall answer, my update is all about formatting the time as required. Reduced Programming Lines
<div id="liveClock"> </div>
$(document).ready(function () {
updateClock();
});
function updateClock() {
document.getElementById('liveClock').innerHTML = new Date().format("dd/MMMM/yyyy hh:mm:ss tt");
}
setInterval(updateClock, 1000);
function timeClock()
{
setTimeout("timeClock()", 1000);
now = new Date();
alert(now);
f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
document.getElementById("foo").innerHTML = f_date;
}
<span id="foo"></span>
Related
I am having this simple countdown:
function offer_countdown_timer(countdown_start, countdown_time, update, complete) {
var start = new Date(countdown_start).getTime();
var interval = setInterval(function() {
var now = countdown_time-(new Date().getTime()-start);
if( now <= 0) {
clearInterval(interval);
complete();
} else {
update(Math.floor(now/1000));
}
},100); // the smaller this number, the more accurate the timer will be
}
and here I call it:
<script>
offer_countdown_timer(
'<%= s.created_at%>',
3600000, // 1 hour in milliseconds
function(timeleft) { // called every step to update the visible countdown
var txt = timeleft+' seconds';
$('#tender_countdown_<%= s.id %>').html(txt);
//$('#tender_countdown_<%= s.id %>').html(moment(txt).format('HH:mm:ss'));
},
function() {
$('#product_<%= s.id %>').html('Offer has expired!');
}
);
</script>
Output of this is:
773 seconds
(and it's counting down)
I'd like to see something like this (HH:ss:mm):
00:12:53
(and counting it down).
I tried this to use this (with using the Moment.js lib - https://momentjs.com/docs/):
$('#tender_countdown_<%= s.id %>').html(moment(txt).format('HH:mm:ss'));
But in this case, the output is this:
01:00:00
The time information is wrong, and it's not counting down. Why is that? How do I properly format the countdowning time?
Thank you
The number of seconds is an abstract duration of time, rather than a date representing a specific moment in time. Moment's constructor expects you to give it a date string.
Moment has a Duration object which can parse your data. It doesn't have nice formatting functions yet, but you can construct the desired output easily enough:
var txt = 773;
var m = moment.duration(txt, "s");
var output = m.hours() + ":" + m.minutes() + ":" + m.seconds();
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
See https://momentjs.com/docs/#/durations/ for more details.
I need help with setting my timeout for the function. I'm trying to set the timeout for a given date and time but my conversion of them to milliseconds is not working.
Here's my code. Please help.
<script>
var ref = firebase.database().ref().child("Message");
var newRef = ref.child("20161227125916539")
newRef.on('value',function(snap){
heading.innerText =snap.child("message").val();
});
ref.on("child_added",function(snap){
var date = snap.child("date").val();
var time = snap.child("time").val();
var type = snap.child("type").val();
var venue = snap.child("venue").val();
var route = snap.child("route").val();
var message = snap.child("message").val();
date = date + time;
date = date.getTime();
var now = new Date();
now = now.getTime();
set = date - now;
var explode = function(){
alert("Boom!");
};
setTimeout(explode, 2000);
});
</script>
You need to parse the date using new Date().
As you said, the value of date is "2016-12-27" and the value of time is "15:30", so while concatenating them, you also need an extra space. Something like:
date = date + " " + time;
var someDate = new Date(date);
var now = new Date();
var diffInMillis = now - someDate
var explode = function(){
alert ("Boom!");
}
setTimeout(explode, diffInMillis);
dateobj=new Date(datestring);
timeinmilliseconds=dateobj.getTime();
//by the way, may check the browsers console if sth is not working:
datestring.getTime();// error:undefined function
Youre calling the getTime function on a string. You need to convert it into a time obj first. Be aware of the right String format. There are good resources online.
The better Way:
A timeout is killed when the browser is reloaded. Thats bad. It would be better to store the time, and regularily check if the time is reached. That would survive reloads, crashes, shutdowns etc:
function set(timestring){
localStorage.setItem("timer",new Date(timestring).getTime());//store timer
check();//start checking
}
function check(){
if(var await=localStorage.getItem("timer")){//if timer is set
var now=new Date().getTime()
if(await<=now){//time reached, or reached in the past
alert("Yay, timer finished");
}else{//not reached yet
console.log(await-now+" left");//log the time left
setTimeout(check,1000);//check again in a scond
}}
window.onload=check;// browser started, check for an existing timer
Use like this:
set("28-12-2016 12:30");
I have a start date defined in a database and I need to know when the start date is greater then the current time. I've tried using setInterval, but I can't access the updated time outside the setInterval function.
This is what I need to compare the current time to the database variable:
if(startDate > now) {
var status = 'pre';
}
I've tried using setInterval as follows, but I can't access the updated (current time) outside of the setInterval function.
setInterval(function(){
now = moment(new Date()).format();
console.log('time1 ', now); // this works
}, 1000);
console.log('time2 ', now); // this doesn't
What am I doing wrong?
Try this..
var now = new Date();
setInterval(function(){
now = new Date();
console.log('time1 ', now.getHours()+":"+now.getMinutes()+":"+now.getSeconds());
}, 1000);
console.log('time2 ', now.getHours()+":"+now.getMinutes()+":"+now.getSeconds());
});
I ended up using react-interval https://github.com/nkbt/react-interval to accomplish this.
I'm trying to get the current date without the time and store it in a variable, within JavaScript. It needs to be without time as I'm converting it to an epoch date, with which I will use to measure the past 24 hours (if date is within 24 hours then it will be displayed). The problem is that with the added time, it doesn't match as within the last 24 hours.
e.g. it returns the date as the following when converted to epoch: 1408704590485
I want it to be like 1408662000000
I'm not to sure how to do this.
Code - How the current days epoch date is currently being stored -
var epochLoggingFrom;
var epochLoggingTo;
$(document).ready(function () {
epochLoggingFrom = dateToEpoch(new Date());
epochLoggingTo = dateToEpoch(new Date());
}
dateToEpoch function -
function dateToEpoch(thedate) {
return thedate.getTime();
}
Try this:
function dateToEpoch(thedate) {
var time = thedate.getTime();
return time - (time % 86400000);
}
or this:
function dateToEpoch2(thedate) {
return thedate.setHours(0,0,0,0);
}
Example : http://jsfiddle.net/chns490n/1/
Reference: (Number) Date.prototype.setHours(hour, min, sec, millisec)
Try this:
var nowDate = new Date();
var date = nowDate.getFullYear()+'/'+(nowDate.getMonth()+1)+'/'+nowDate.getDate();
Note: Adjust format as you want, like reorder day, month, year, remove '/' and get combined date etc.
or use this:
dateToEpoch(new Date().toLocaleDateString())
I tried using javascript. this method returns the current date in "DD/MM/YYYY" format.
getCurrentDate() {
const t = new Date();
const date = ('0' + t.getDate()).slice(-2);
const month = ('0' + (t.getMonth() + 1)).slice(-2);
const year = t.getFullYear();
return `${date}/${month}/${year}`;
}
I have the following situation:
I have a certain function that runs a loop and does stuff, and error conditions may make it exit that loop.
I want to be able to check whether the loop is still running or not.
For this, i'm doing, for each loop run:
LastTimeIDidTheLoop = new Date();
And in another function, which runs through SetInterval every 30 seconds, I want to do basically this:
if (LastTimeIDidTheLoop is more than 30 seconds ago) {
alert("oops");
}
How do I do this?
Thanks!
JS date objects store milliseconds internally, subtracting them from each other works as expected:
var diffSeconds = (new Date() - LastTimeIDidTheLoop) / 1000;
if (diffSeconds > 30)
{
// ...
}
what about:
newDate = new Date()
newDate.setSeconds(newDate.getSeconds()-30);
if (newDate > LastTimeIDidTheLoop) {
alert("oops");
}
You can do like this:
var dateDiff = function(fromdate, todate) {
var diff = todate - fromdate;
return Math.floor(diff/1000);
}
then:
if (dateDiff(fromdate, todate) > 30){
alert("oops");
}
Create a date object and use setSeconds().
controlDate = new Date();
controlDate.setSeconds(controlDate.getSeconds() + 30);
if (LastTimeIDidTheLoop > controlDate) {
...