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");
Related
var startdate = '02.05.2018 18:05:03';
How to find out how many minutes have passed from startdate to now?
My try
var exp = moment(startdate);
minutes = moment().diff(exp, 'minutes');
but result 124764 it not right
Parsing of date strings are not consistent among browsers. Always pass the format of the string if it is in non-ISO format to prevent unwanted bugs:
var exp = moment(startdate, 'DD.MM.YYYY HH:mm:ss');
moment().diff(exp, 'minutes');
To get the difference between two moment time objects, you can use .diff(). Then you can use any of asHours(), asMinutes(), asSeconds() to get human-readable time difference.
var start = moment('02.05.2018 18:05:03');
var end = moment('02.05.2018 18:11:03');
var duration = moment.duration(end.diff(start));
var mins = duration.asMinutes();
console.log(mins)
In your case, you can simply call moment().diff(time) since you want to get difference between the time you specify and now.
var time = moment('02.05.2018 18:05:03');
var duration = moment.duration(moment().diff(time));
var mins = duration.asMinutes();
console.log(mins)
there is a test route in nodejs as shown below
router.get('/testdata', function (req, res) {
var startTime="2016-11-30 23:40:00"
var endTime = new Date("2016-11-30 23:40:00");
endTime.setSeconds(endTime.getMinutes() + 2)
console.log("************getDeviceData*********************")
console.log(startTime)
console.log(endTime);
dataTrackerInfoDetails.timerId = setInterval(function(){
startTime=endTime;
var endTime = new Date(startTime);
endTime= endTime.setSeconds(endTime.getMinutes() + 2)
console.log("************after first*********************")
console.log(startTime)
console.log(endTime);
},dataTrackerInfoDetails.timerInterval*1000);
})
Every 10 seconds i need to get the date format as shown below with 2 minutes increment from the current date
************getDeviceData*********************
2016-11-30 23:40:00
2016-11-30T18:10:42.000Z
************after before*********************
2016-11-30 23:40:00
undefined
But i will get undefined
expected output is
************getDeviceData*********************
Start date 2016-11-30 23:40:00
2016-11-30T18:10:42.000Z
************after before*********************
2016-11-30T18:10:42.000Z
2016-11-30T18:10:44.000Z
************after before*********************
2016-11-30T18:10:44.000Z
2016-11-30T18:10:46.000Z.......
Note the date should be same format 2016-11-30T18:10:44.000Z please let me now how to do it
Your issue is here:
setInterval(function(){
startTime=endTime;
var endTime = new Date(startTime);
The declaration of endTime with var creates a local variable with a value of undefined before the function is executed. So when the line:
startTime=endTime;
is executed, startTime is set to undefined. Then:
var endTime = new Date(startTime);
will assign an invalid date to endTime. Also, where you have:
endTime = endTime.setSeconds(endTime.getMinutes() + 2)
you are mixing setSeconds with getMinutes, and the return value from setSeconds is a time value (i.e. number), not a Date, so even if you fix the other errors, you'll get an error as numbers don't have Date methods.
What you probably want to do is:
// Using an IIFE to mimic a callback
(function(){
// Create start and end as Dates, use valid ISO 8601 format
var startTime = new Date("2016-11-30T23:40:00");
var endTime = new Date("2016-11-30T23:40:00");
// Fix second/minutes mixup
endTime.setMinutes(endTime.getMinutes() + 2);
console.log("************getDeviceData*********************")
console.log(startTime)
console.log(endTime);
// Just call the timer
setInterval(function(){
startTime = endTime;
// Don't declare a local endTime
endTime = new Date(startTime);
// Modify endTime in place and fix seconds/minutes
endTime.setMinutes(endTime.getMinutes() + 2)
console.log("************after before*********************")
console.log(startTime)
console.log(endTime);
}, 1000); // run at 1 second intervals for test
}());
You probably want to put some limit on how often this runs. Keep a reference to the value returned by setInterval and then use it to call clearInterval when some condition is met.
I'm a bit of a newbie so please bear with me. I've created a date object in javascript every time someone opens a new page. I want to save the time the user opened the page and create another date object exactly one day later to create a countdown timer showing time elapsed from date 1 to date 2.
To accomplish this, I tried subtracting the two dates using .getTime; I want to keep the second date static instead of one day ahead of the current time. Unfortunately, this is not happening even though I have confined d2 (Date 2) to a condition that only runs once and is stored in variable nextday. Here's my JS
$(function (){
localStorage.clear()
var ran = JSON.parse(localStorage.getItem('run'))
d1 = new Date()
var i = 0
if(!ran){
i+=1
d2 = new Date(d1)
nextday = d2.setHours(d1.getHours()+24)
console.log(i)
console.log(typeof(nextday))
localStorage.setItem('run',JSON.stringify('ran'))
localStorage.setItem('nextday',JSON.stringify(nextday))
}
console.log(localStorage)
nday = JSON.parse(localStorage.getItem('nextday'))
console.log(nday)
var seconds = (nday - d1.getTime())
console.log(seconds)
console.log(localStorage)
})
Your script is clearing local storage every time the page is loaded:
localStorage.clear()
This will prevent anything from being stored across runs. Remove it.
You're clearing your localStorage before you access your locally-stored data. Thus, your ran variable is always empty. Remove that one call to clear(), and everything should work fine.
$(function() {
// localStorage.clear() <= the offending code!
var ran = JSON.parse(localStorage.getItem('run'))
d1 = new Date()
var i = 0
if (!ran) {
i += 1
d2 = new Date(d1)
nextday = d2.setHours(d1.getHours() + 24)
console.log(i)
console.log(typeof(nextday))
localStorage.setItem('run', JSON.stringify('ran'))
localStorage.setItem('nextday', JSON.stringify(nextday))
}
console.log(localStorage)
nday = JSON.parse(localStorage.getItem('nextday'))
console.log(nday)
var seconds = (nday - d1.getTime())
console.log(seconds)
console.log(localStorage)
})
I'm looking for a way to shift the browser's Date to a specified one without freezing time. Let's pretend I have some function shiftDate() which does just that. The following outlines the behavior I'm seeking:
// Here's the current time.
new Date().getTime(); //=> 1391109350382
//
// Now let's call the function to shift/travel back in time and _immediately_
// check the time afterwards
shiftDate('2014-01-01');
new Date().getTime(); //=> 1388534400000
//
// Now let's wait 1111 ms and then check the time again
new Date().getTime(); //=> 1388534401111
//
// Let's wait another 1111 ms
new Date().getTime(); //=> 1388534402222
//
// Let's shift/travel back in time once more
shiftDate('2014-01-01');
new Date().getTime(); //=> 1388534400000
//
// Then wait 1111 ms again
new Date().getTime(); //=> 1388534401111
//
// And wait 1111 ms again
new Date().getTime(); //=> 1388534402222
Notice time keeps ticking after each shift. Most solutions that I've found entirely freeze time through a mock or stub of some sort. However, freezing time is not an appropriate solution: doing so disrupts other time-dependent features such as animations. Below is an example, which freezes time:
new Date().getTime(); //=> 1391109350382
var oldDate = Date;
Date = function() { return new oldDate('2014-01-01'); };
var testDate = new Date();
new Date().getTime(); //=> 1388534400000
// Wait 1111 ms, ten minutes, or an hour: time will never change
new Date().getTime(); //=> 1388534400000
Check out Momentjs for handy date and time manipulation.
http://momentjs.com/
// Let's shift/travel back in time once
shiftDate('2014-01-01');
new Date().getTime(); //=> 1388534400000
I'm not sure why you don't simply do new Date('2014-01-01').getTime(); in your custom, shifted logic?
However, you can get the desired behaviour with the following function:
function shiftDate(to) {
var realDate = Date;
Date = function frozenDate() {
Date = realDate;
return new Date(to);
};
}
When you call shiftDate, the next - and only the next - call to Date will yield a date from a confused timeline.
I dont think there is any way you can change the date objects internal time pointer (if you want to call it that) without going deep into the OS. I think you'd have to write your own little library, similar to this:
var myDate = function(dateStr){
var initTime = new Date().getTime()
var dateObj = new Date(dateStr);
var myDateTime = dateObj.getTime();
// subtract the init time from the time this method is called
// to get a difference, then add it to your "old" time to get
// the updated millisecond value
this.getTime = function(){
var currentTime = new Date().getTime();
var dif = currentTime - initTime;
return myDateTime + dif;
};
};
You could of course get fancy with the methods and implement all of the native Date object methods.
I've got it! The trick is to keep track of the time change within a new Date prototype. Here's a rough implementation:
function shiftDate(date) {
window.trueDate = window.trueDate || Date;
var trueStart = new trueDate().getTime();
var shiftedStart = new Date(date).getTime();
Date = function() {
var timeChange = new trueDate() - trueStart;
return new trueDate(shiftedStart + timeChange);
}
}
And here's a simple test:
shiftDate('2014-01-01')
testDate = new Date();
setInterval(function(){
console.log(new Date().toString());
}, 1000);
I have the following data:
var currentTime: 2013-07-11 15:55:36+00:00
var currentTimezone: Africa/Asmera
I need a way to convert the currentTime in UTC to a new time based on currentTimezone.
I've looked into Timezone.js and I'm having trouble implementing it (the directions on the site are a little ambiguous)
The code for the function I'm intending on using is included. Thanks :)
<script>
$("#storeTime").click(function(){
storeCurrentTime();
})
$("#getTime").click(function(){
retrieveTime();
})
$("#storeTimezone").click(function(){
var yourTimezone = $('#timezone-select').find(":selected").text();
tz = yourTimezone.toString();
storeCurrentTimezone(tz);
})
$("#convertTime").click(function(){
//get the most recent UTC time, clean it up
var currentTime = $('#RetrievedTime').html();
currentTime = currentTime.split(": ")[1];
$('#convertedTime').html("Converted Time: " + currentTime);
//get the saved timezone
var currentTimezone = $('#storedTimezone').html();
})
</script>
You're going to need to know the timezone offset, so some sort of dictionary with strings to numbers.
// assuming your dictionary says 3 hours is the difference just for example.
var timezoneDiff = 3;
Then you can just make a new time like this
// Assuming you have the proper Date string format in your date field.
var currentDate = new Date(currentTime);
// Then just simply make a new date.
var newDate = new Date(currentDate.getTime() + 60 * 1000 * timezoneDiff);
Update
I've written a javascript helper for this which you can find at:
http://heuuuuth.com/projects/OlsonTZConverter.js
I pulled the timezone data from the wikipedia page https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
Usage is as follows once included the script.
var offset = OlsonTZConverter.GetUTCOffset("Africa/Asmera");
or if there is Daylight Savings in effect:
var offset = OlsonTZConverter.GetUTCOffset("Africa/Asmera",true);
These will throw if you pass an invalid timezone, but you can check if a timezone is valid with:
var isValid = OlsonTZConverter.Contains("Africa/Asmera");
or just look at the entire dictionary with:
var tzDict = OlsonTZConverter.ListAllTimezones();
Hope this maybe saves someone some time sometime :).