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

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.

Related

why are the dates not being generated properly?

I am using a function in Angular JS to generate the dates for the past one week starting from today's date. I am storing these dates in an array and then using that array to flood a dropdown.
The following is the code that is being used by me.
generate() {
this.date_new = [];
var date = new Date();
var date1 = new Date();
for (var i = 0; i < 7; i++) {
date.setDate(date1.getDate() - i);
var a = date.toString();
var str = this.convert(a);
this.date_new.push(str);
}
}
Here convert is a function which is being used to convert the dates to the required format. A screenshot of generated dates is attached below.
As evident from the screenshot, the last two dates are incorrect. Can somebody explain to me, what the problem is?
The setDate() method sets the day of the Date object relative to the
beginning of the currently set month.
The above is from MDN.
Your code works for the first 5 dates, but once you are modifying your February date with -1, it sets the day relative to the current month e.g. February. So this will turn into January (as you are setting the day to -1), same happens in the next iteration and you get December.
For an easy fix you can just set the date variable to new Date() in the first line of your for loop.
The issue here is using the same date variable in the loop. You need to re-initialize it.
As can be seen in Parameters Value section in the link here. Zero and negative values in setDate() sets the date from previous month.
Hence at setDate(0), date value is set to last day of Feb. Now since you are using the same variable, setDate(-1) takes the previous month from Feb hence you get Jan.
You need to change the code to something like this:
generate() {
this.date_new = [];
var date1 = new Date();
for (var i = 0; i < 7; i++) {
// re-initialize date
var date = new Date();
date.setDate(date1.getDate() - i);
var a = date.toString();
var str = this.convert(a);
this.date_new.push(str);
}
}
Hope this helps :)
The issue here is that negative numbers inside the setDate method don't work quite well.
Please update the code to something like below:
this.date_new = [];
var date = new Date();
var date1 = new Date();
for (var i = 0; i < 7; i++) {
date= new Date(date1.getFullYear(), date1.getMonth(),date1.getDate()-i);
var a = date.toString();
var str = this.convert(a);
this.date_new.push(str);
}
Hope this will solve your problem.

Setting a date without Setting TIme Javascript

I m trying to do the following :
Storing Current day +1 (Tomorrow's date) ( CurrentDay is the StartDay,wrong naming alias,my bad)
calculating 7 days from date from 1st Step
Everyday checking presentDay, and if is equal to 7th day, run my logic.
Problem I m facing is :
The DateObject I store is in a numerical format and it also saves the time. I want only the date for comparison.
Is it possible to directly compare dates? I do not really wish to use 3rd party library.
Any help will be appreciated.
Code :
var d = new Date();
var stdate = d.setDate(d.getDate() + 1); //output something like 1526407850028 ( last few digits changes every second)
var weeklyDate = new Date();
var wkdate = weeklyDate.setDate(weeklyDate.getDate() + 7); //output Ex : 1526926307437
var presentDay = new Date();
var pdate = presentDay.setDate(presentDay.getDate());
if (pdate == wkdate) { // I want only date comparison
// my logic
}
Try keeping your steps more separate. For instance, why not just compare the date values by calling Date.prototype.getDay()? Then you're not working with all of that other stuff. You can also reduce the number of calls to new Date(), so the whole thing would be:
//calculate target date
let d = new Date(); // returns an integer between 0-6
var stDay = (d.getDay()+1)%7; //tomorrow's day of week kept between 0-6 by modulus
//daily check runs in separate function
let today = new Date();
if( today.getDay() === stDay){
//logic
}
developer.mozilla.org - Date.prototype.getDay()

How to keep Date object static and avoid updating?

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

parse.com - how i can create query equal createdAt by date only with javascript

I want to find data by "createdAt" field but i need to search with date only (without time).
var d = new Date();
var query = new Parse.Query("TableName");
query.equalTo("createdAt", d);
What you basically have to do to generate two dates:
date at 0:0:0 time
date+1day at 0:0:0 time
Then search for:
query.greaterThanOrEqualTo('createdAt', date);
query.lessThan('createdAt', datePlusOne);
This effectively gives you the range of dateT0:0:0 - dateT23:59:59.99999 inclusive, but in a safe way
If you want to use pure JavaScript:
// assuming date is the date/time to start from
date.setHours(0, 0, 0, 0);
// hours/min/sec/ms cleared
var datePlusOne = new Date(date);
datePlusOne.setDate(datePlusOne.getDate() + 1);
You can also use the moment library to make your code easier to read/maintain. This library is also used server-side in parse.com, though it is an older version.
m1 = new moment(date);
m1.startOf('day');
m2 = new moment(m1);
m2.add(1, 'day');
// convert moment back to JavaScript dates
date = m1.toDate();
var datePlusOne = m2.toDate();
Full solution using moments:
var d = new Date();
var query = new Parse.Query("TableName");
var start = new moment(d);
start.startOf('day');
// from the start of the date (inclusive)
query.greaterThanOrEqualTo('createdAt', start.toDate());
var finish = new moment(start);
finish.add(1, 'day');
// till the start of tomorrow (non-inclusive)
query.lessThan('createdAt', finish.toDate());
query.find.then(function(results) {
// use results
});
If you are looking for results, filtered by "created today", you could do this:
var moment = require("moment");
var start = moment().sod() //Start of day
var end = moment().eod() //End of day
var query = new Parse.Query("myClass")
query.greaterThanOrEqualTo("createdAt", start.format());
query.lessThan("createdAt", end.format());
query.find({...});
Of course, if you are looking for a greater timespan than "today", you would go with Timothy's answer.
This code has been tested in Parse Cloud Code with Momentjs 1.7.2

new Date() - object is not a function

I'm working in AngularJS, but I'm experiencing an error when working with dates. I currently have one Unix timestamp, and I need to find out if it is today.
var start = new Date();
start.setHours(0,0,0,0);
var end = new Date();
end.setHours(23,59,59,999);
// Convert to Second/Unix Timestamp
start = Math.round(start.getTime() /1000);
end = Math.round(end.getTime() /1000);
for (i = 0; i < list.length; i++) {
var date = Date.utcDateToTimestamp(list[i].date_utc);
if(start < date && end > date)
console.log('this one is today');
}
However, I'm getting an error in the console:
TypeError: object is not a function
I've looked into it, and it seems I can't even create a new Date object without this being thrown:
var start = new Date();
Is this something really obvious, or..?
Maybe look for simple solution:
//Get today's date
var todaysDate = new Date();
//call setHours to take the time out of the comparison
if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0));
{
//Date equals today's date
}
You don't need to check for hours, reset hours to zero and compare them. You are interested in year, month, day only:)

Categories