How to keep Date object static and avoid updating? - javascript

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)
})

Related

Setting the milliseconds on Timeout based on given date time

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");

.getMonth() and .setDate not working properly when day number exceeds month

Good evening stack. I have this, half made, half copied function which in theory should take a desired date, and append it in a div with 7 next days ahead:
//GLOBAL VARIABLES
var startDate = new Date();
var nextDate = new Date();
var prevDate = new Date();
function GetDates(tDate) {
var aryDates = [];
$("#calendar").empty();
for(var i = 0; i <= 7; i++) {
var currentDate = new Date();
currentDate.setDate(tDate.getDate() + i);
$("#calendar").append("<div class='calendar-day'><p class='weekday'>"+DayAsString(currentDate.getDay())+"</p><p class='day'>"+currentDate.getDate()+"</p><p class='month'>"+MonthAsString(currentDate.getMonth())+"</p><p class='daytime'>Rano</p><p class='daytime'>Popołudnie</p><p class='daytime'>Wieczór</p></div>");
}
nextDate.setDate(tDate.getDate() + 7); //THIS CAUSES THE PROBLEM
prevDate.setDate(tDate.getDate() - 7); //THIS CAUSES THE PROBLEM
console.log("Next Date: " + nextDate);
console.log("Previous Date: " + prevDate);
}
And is fired from jquery document ready:
$(document).ready(function(){
GetDates(startDate); wartosciami od dnia dzisiejszego
var navright = $(".calendar-nav-right");
var navleft = $(".calendar-nav-left");
navright.on("click", function(){GetDates(nextDate);});
navleft.on("click", function(){GetDates(prevDate);});
//console.log(aryDates);
});
The problem lies specifically in the two setDate lines with a comment. It works completely fine untill the result might go beyond a specific calendar month (ie. for april, it will go nuts if the result is > 30).
In the current setting, if I'd click the navleft button causing the calendar to go forward a few times, and print the value of "nextDate" it show me the correct date, yet the dates itself would go in this order:
17april, 18april, 19april, 20april, 21april, 22april, 23april
24april, 25april, 26april, 27april, 28april, 29april, 30april
1april, 2april, 3april, 4april, 5april, 6april, 7april
The only moments when it would shift to another month would be when it fires of on the way, like this:
28april, 29april, 30april, 1may, 2may, 3may, 4may
And when I'd start mixing the next and previous calendar, it gets even more messed up with the starting dates.
I've been seeting at this for 3 hours now and can't find a way to make it work properly.
The error can be found HERE under the tab "2) Wybierz Date"
Any help on the topic would be gratefuly appreciated

How to check condition on time

Hi i want to put condition on time that only time between 9:00 AM to 5:00 PM has to access.
here is my javascript code for it.
var time = document.getElementsByName('s_time')[0].value;
if user enter tie before 9:00 AM or after 5:00 PM it should give alert. Please help me
User enterd time by using jquery picker.
This is not complete solution, But hope this will help you
Get current time Get in milliseconds,
the time difference between
next execution time minus current time Settimeout with result
millisecons
Here is simple example
You just need to calculate the difference between the current time and the target time and use setTimeout() with that value.
For example, depending on how your target browsers parse dates, you could do the following:
function alert3pm() {
alert("It's 3PM!");
}
var timeAt3pm = new Date("1/31/2011 03:00:00 PM").getTime()
, timeNow = new Date().getTime()
, offsetMillis = timeAt3pm - timeNow;
setTimeout(alert3pm, offsetMillis);
Or rather, instaed of parsing a date (since that's really inconsistent between browsers) you could do something like this:
function getTimeAtHour(hour) {
var t = new Date();
t.setHours(hour);
t.setMinutes(0);
t.setSeconds(0);
t.setMilliseconds(0);
return t;
}
http://www.w3schools.com/jsref/jsref_obj_date.asp
var time = document.getElementsByName('s_time')[0].value || new Date().getTime();
var d = new Date(time);
var currentHour = d.getHours();
if (currentHour < 9 || currentHour >= 17) {
alert('something');
}

Trying to get countdown with current time versus the days closing time javascript

http://jsbin.com/ocuceb/6/edit
The above link is where the full code is, I am trying to get a count down timer of how many hours and minutes are left till a business closes.
function countDown() {
var d = new Date();
var hour = d.getHours();
if(hour<10){hour="0"+hour;}
else if(hour>12){hour=hour - 12;}
var minutes = d.getMinutes();
if(minutes<10){minutes="0"+minutes;}
var seconds = d.getSeconds();
if(seconds<10){seconds="0"+seconds;}
var open = weekday[day.getDay()].open.replace(/am/g,'');
var close = weekday[day.getDay()].close.replace(/pm/g,'');
open = parseInt(open,10);
close = parseInt(close,10);
//confused here!
var timeClose = close;
var timeRemaining = Math.floor(d.getHours() - timeClose);
document.write('<br><br>Close At: '+timeClose+"pm<br>Time Remaining:"+timeRemaining);
}
And that is where I am having the trouble, I can get the time of being opened and the time of being closed. Originally I tried this
var timeClose = parseInt(close+':00:00',10);
var difference = Math.floor(d.getDay() - timeClose);
And of course this didn't work, it either said Undefined or NaN I'm not sure how to go about this, the timing is all new to me never needed this though a client asked for this. Where it states the Actual Time, What time they close, and show an image if the time is within the open to close time (basically an Open Neon Sign) and when past closed (a closed Neon Sign)... I figured it would be very simple, though I am having so tricky corners to pass.
JavaScript time does not think in 12-hour format. It thinks in 24-hour format. Change your array of objects to reflect (22 being 10pm):
hours[0]= {open:"8:00:00",close:"22:00:00"};
hours[1]={open:"8:00:00",close:"22:00:00"};
hours[2]={open:"8:00:00",close:"22:00:00"};
hours[3]={open:"8:00:00",close:"22:00:00"};
hours[4]={open:"8:00:00",close:"22:00:00"};
hours[5]={open:"8:00:00",close:"22:00:00"};
hours[6]={open:"8:00:00",close:"22:00:00"};
Also, parsing an int like this could lead to issues:
var timeClose = parseInt(close+':00:00',10);
You should substring everything between the colons to get your desired hours or minutes.
var timeClose = parseInt(open.substring(0,open.indexOf(":")),10);
Also with the way you have it set up, during business hours (or before 10pm), you will always have a negative number because you subtract the current hours from the close time. If it's 8pm and the close time is 10pm, we will have -2 hours remaining? Switch the operands to subtract getHours from time instead:
var timeRemaining = Math.floor(timeClose - d.getHours());
After that, you can probably check timeRemaining for a negative value. If it is negative, that means the business is closed, and you can modify your output message to reflect as such, i.e.
var timeRemaining = Math.floor(timeClose - d.getHours());
if (timeRemaining < 0) {
output = "Sorry we are closed already";
} else {
output = "You have " + timeRemaining + " to come in and shop till you drop";
}
I think a simpler way to do this would be something like this
var now=new Date();
var closing=new Date(now.getFullYear(),now.getMonth(),now.getDate(),21);//Set this to 10:00pm on the present day
var diff=closing-now;//Time difference in milliseconds
if(now.getHours<7){
//It's before opening time
}
else if(diff<0){
//It's after closing time
}
else{
var hours=Math.floor(diff/(1000*60*60));
diff=diff%(1000*60*60);
var mins=Math.floor(diff/(1000*60));
diff=diff%(1000*60);
var secs=Math.floor(diff/(1000));
}
Here is a reference on the time object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Why does Safari/Opera not work with this javascript code?

I am working on a calendar that will show bookings. The height of containing the booking is calculated dynamically in proportion to the length of the booking. The following code works perfectly well in Firefox but not in Safari or Opera:
function calculateBookingHeight(from, to) {
var today = new Date;
var end = new Date.UTC(today.getUTCFullYear(),today.getUTCMonth(),today.getUTCDate(),23);
var start = new Date.UTC(today.getUTCFullYear(),today.getUTCMonth(),today.getUTCDate(),6);
var from = new Date(from);
var to = new Date(to);
if (from > start && to < end) {
var difference = (to - from) / 120000;
} else if (from > start && to > end) {
var difference = (end - from) / 120000;
} else {
var difference = 510
}
return difference;
}
In summary, each hour on the calendar is a height of 30px. The second if statement deals with the end of the booking being the following day.
If I replace the entire code block with return 510, Safari behaves as expected and sets the height of each booking to 510px so I assume it must be something in this function that is causing the problem.
Any help would be appreciated.
Thanks
Robin
One of your problems is that
var end = new Date.UTC(today.getUTCFullYear(),today.getUTCMonth(),today.getUTCDate(),23);
var start = new Date.UTC(today.getUTCFullYear(),today.getUTCMonth(),today.getUTCDate(),6);
should be
var end = new Date(today.getUTCFullYear(),today.getUTCMonth(),today.getUTCDate(),23);
var start = new Date(today.getUTCFullYear(),today.getUTCMonth(),today.getUTCDate(),6);
In other words, UTC is a getter method, which is why you were getting an object. To construct a date with those arguments, just pass them to the constructor.
Using
var end = today ;
end.setUTCHours(23) ;
would be more straightforward.
http://www.w3schools.com/js/js_obj_date.asp
Describes creation of a javascript date object with four constructors:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Your invocation without parens isn't valid js, as Luis points out.
Figured it out. The dates weren't being created properly from the variables passed into the function. I needed to separately parse the input before creating the dates.

Categories