Odd date behaviour - javascript

Using the following code, up until this week, the object was returning a drop-down with the "correct" weeks, i.e. week 36 as 5th september, 37 as 12th september, etc.
Since the month has changed to October, the weeks are now being returned incorrectly.
Code from LEAP.Schedule object:
/* --- LEAP Namespace --- */
var LEAP = {};
/* --- LEAP.Schedule Object --- */
LEAP.Schedule = function(){//init
this.weeks = [];
this.calculateWeeks();
};
LEAP.Schedule.prototype.calculateWeeks = function(){
this.date = new Date ( 2011, 8, 5 ); // First week of new school year
this.num = 36; // Calendar number of this week
this.weeks.push(new LEAP.Schedule.week(this.date, this.num));
for (var i = 1; i < 51; i++) {
var week = i * 7;
var updated_date = new Date ();
updated_date.setDate(this.date.getDate() + week);
if (this.num > 51) {
this.num = 0;
}
this.num++;
this.weeks.push(new LEAP.Schedule.week(updated_date, this.num));
}
};
LEAP.Schedule.prototype.getWeeks = function(){
return this.weeks;
};
/* --- LEAP.Schedule.week Object --- */
LEAP.Schedule.week = function(n_date, n_week){
this.week = n_week;
this.date = n_date;
this.year = this.date.getFullYear();
this.month = this.date.getMonth();
this.month += 1;
this.day = this.date.getDate();
var mydate = new Date(this.date);
this.end_date = mydate.setDate(mydate.getDate() + 6);
};
LEAP.Schedule.week.prototype.getJSDate = function(){
return this.date;
};
LEAP.Schedule.week.prototype.getStartDate = function(){
return this.year + "-" + pad(this.month) + "-" + pad(this.day);
};
LEAP.Schedule.week.prototype.getEndDate = function(){
end_of_week = new Date(this.end_date);
var year = end_of_week.getFullYear();
var month = pad(end_of_week.getMonth() + 1);
var day = pad(end_of_week.getDate());
return year + "-" + month + "-" + day;
};
LEAP.Schedule.week.prototype.getLabel = function(){
return "Week " + this.week + ": " + this.day + (this.day==1||this.day==21||this.day==31?"st":this.day==2||this.day==22?"nd":this.day==3||this.day==23?"rd":"th") + " " + ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][this.month-1] + " " + this.year;
};
pad = function (n) {
return n>9 ? n : "0"+n;
};
Code initialising/displaying this Object:
WeeklyUpdate.init = function() {
var Scheduleobject = new LEAP.Schedule();
var weeks = Scheduleobject.getWeeks();
var dispHTML = '<p>weeks.length: ' + weeks.length + '</p>';
for (var i = 0; i < weeks.length; i++) {
if (i % 2 > 0) {
dispHTML += '<div style="background:#ccc;">';
} else {
dispHTML += '<div style="background:#fff;">';
}
dispHTML += '<p>i: ' + i + '</p>';
dispHTML += '<p>getJSDate: ' + weeks[i].getJSDate() + '</p>';
dispHTML += '<p>getStartDate: ' + weeks[i].getStartDate() + '</p>';
dispHTML += '<p>getEndDate: ' + weeks[i].getEndDate() + '</p>';
dispHTML += '<p>getLabel: ' + weeks[i].getLabel() + '</p>';
dispHTML += '</div>';
}
$('div#wrapper').html(dispHTML);
//WeeklyUpdate.displayWeekFilter(weeks);
}
Output (trimmed after three weeks):
weeks.length: 51
i: 0
getJSDate: Mon Sep 05 2011 00:00:00 GMT+0100 (GMT Daylight Time)
getStartDate: 2011-09-05
getEndDate: 2011-09-11
getLabel: Week 36: 5th Sep 2011
i: 1
getJSDate: Wed Oct 12 2011 13:58:02 GMT+0100 (GMT Daylight Time)
getStartDate: 2011-10-12
getEndDate: 2011-10-18
getLabel: Week 37: 12th Oct 2011
i: 2
getJSDate: Wed Oct 19 2011 13:58:02 GMT+0100 (GMT Daylight Time)
getStartDate: 2011-10-19
getEndDate: 2011-10-25
getLabel: Week 38: 19th Oct 2011
I've looked through this a few times but I'm getting rather confused! Any ideas? I'm sure it's something pretty obvious.
Cheers

When you initialize a new Date() it defaults to the current date. getDate only refers to the day, not the month or year. Your code worked in September because that was the same as the start month, but since it is now October, you are offsetting from the wrong month.
var updated_date = new Date ();
should be
var updated_date = new Date (2011, 8, 5);
That way you are offsetting from the start of the school year, not today.
Demo: http://jsfiddle.net/aXgk6/

Use this code, and change the base date to the this.week variable.
I've also applied a change to the part of the code which determines a new week. Otherwise, you would be back near the end of this calender year, asking why your code is broken ;)
LEAP.Schedule.prototype.calculateWeeks = function(){
this.date = new Date ( 2011, 8, 5 ); // First week of new school year
this.num = 36; // Calendar number of this week
this.weeks.push(new LEAP.Schedule.week(this.date, this.num));
var not_new = true;
for (var i = 1; i < 51; i++) {
var week = i * 7;
var updated_date = new Date(this.date);
updated_date.setDate(this.date.getDate() + week);
if (not_new && updated_date.getYear() > this.date.getYear() ) {
not_new = this.num = 0;
}
this.num++;
this.weeks.push(new LEAP.Schedule.week(updated_date, this.num));
}
};

Related

how can get particular day of date when you have start and end date

I have a start date 4/10/2021 and end date 4/12/2021
I want get Tuesday, Thursday and Friday date in jquery
I found this solution:
var x = new Date();
//set the financial year starting date
x.setFullYear(2021, 10, 04);
//set the next financial year starting date
var y = new Date();
y.setFullYear(2021, 12, 04);
var j = 1;
var count = 0;
//getting the all fridays in a financial year
for ( var i = 0; x<y; i += j) {
if (x.getDay() == 5) {
$("#append_text").append("Date : " + x.getDate() + "/"
+ (x.getMonth() + 1) + "<br>");
x = new Date(x.getTime() + (7 * 24 * 60 * 60 * 1000));
j = 7;
count++;
} else {
j = 1;
x = new Date(x.getTime() + (24 * 60 * 60 * 1000));
}
}
$("#append_text").append("total fridays : " + count + "<br>");
but it return only Friday and i think it doesn't work truly
The result is:
Date : 5/11
Date : 12/11
Date : 19/11
Date : 26/11
Date : 3/12
Date : 10/12
Date : 17/12
Date : 24/12
Date : 31/12
total fridays : 9
The solution link is here:
Get Friday Dates of Year in javascript using jquery
do you have any solution for that?
As mentioned in getDay() docs:
The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday.
So, clearly
if (x.getDay() == 5)
5 here stands for Friday. So, if you also need Tuesday as 2 & Thursday as 4, you simply need to modify for loop like:
var day = x.getDay();
if (day === 2 || day === 4 || day === 5)
Demo:
var x = new Date();
//set the financial year starting date
x.setFullYear(2021, 10, 04);
//set the next financial year starting date
var y = new Date();
y.setFullYear(2021, 12, 04);
var html = '';
var count = 0;
//getting the all fridays in a financial year
for (var i = 0; x < y; i++) {
var day = x.getDay();
if (day === 2 || day === 4 || day === 5) {
html += "Date : " + x.getDate() + "/" + (x.getMonth() + 1) + "<br>";
if (day === 5)count++;
}
x.setDate(x.getDate() + 1)
}
$("#append_text").append(html);
$("#append_text").append("total fridays : " + count + "<br>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=append_text></div>
Try this.
var start = new Date(2021, 10, 04);
var end = new Date(2021, 12, 04);
var tuesdays = [], thursdays = [], fridays = [];
for (var current = start; current <= end; current.setDate(current.getDate() + 1)) {
var day = current.getDay();
switch (day) {
case 2: // tuesdays
tuesdays.push(formatDate(current));
break;
case 4: // thursdays
thursdays.push(formatDate(current));
break;
case 6: // fridays
fridays.push(formatDate(current));
break;
default: //other dates
break;
}
}
function formatDate(d) { // formats date to dd/mm/yyy
return d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear();
}
console.log(tuesdays.length + " Tuesdays: ", tuesdays.join('\t'));
console.log(thursdays.length + " Thursdays: ", thursdays.join('\t'));
console.log(fridays.length + " Fridays: ", fridays.join('\t'));
You can do this by iterating over every date between the two dates and saving the ones that fit some criterion, or you can get the first of the required dates, then add 7 days to get each weekly until the end date, e.g.
// Parse date in day/month/year format
function parseDMY(s) {
let [d, m, y] = s.split(/\D/);
return new Date(y, m-1, d);
}
// Get next day by dayNumber on or after date, default today
function getDayOfWeek(day, date) {
let d = date? new Date(+date) : new Date();
d.setDate(d.getDate() - d.getDay() + day +
(day < d.getDay()? 7 : 0));
return d;
}
// Format date as dd/mm/yyyy
function formatDMY(date) {
return date.toLocaleString('en-GB', {
year : 'numeric', // remove if year not required
month: '2-digit',
day : '2-digit'
});
}
// Given start and end date, get days by day number between
// dates inclusive
function getDaysBetweenDates(d0, d1, ...days){
let dStart = parseDMY(d0);
let dEnd = parseDMY(d1);
// Guard against endless loop
if (dEnd < dStart) return;
let dates = [];
while (dStart <= dEnd) {
days.forEach(day => {
let d = getDayOfWeek(day, dStart);
if (d <= dEnd) dates.push(formatDMY(d));
});
dStart.setDate(dStart.getDate() + 7);
}
return dates.sort(
(a, b) => a.split(/\D/).reverse().join('').localeCompare(
b.split(/\D/).reverse().join(''))
);
}
// Get all Tue, Thu and Fri between 4 Oct 2021 and 4 Dec 2021 inclusive
console.log(getDaysBetweenDates('4/10/2021', '4/12/2021', 2, 4, 5));
I've left the year in the date, it's easily removed by removing year: 'numeric', from the formatting options.
Note that in the OP:
y.setFullYear(2021, 12, 04);
creates a Date for 4 Jan, 2022 not 4 Dec 2021 because months are zero indexed, so December is 11. A month value of 12 rolls over to January of the following year.

Check if is between 2 dates [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Closed 4 years ago.
I need to check whether a string is between NOW and 5 minutes ago
I've managed to get the current date + time and the 5 minutes ago, but I'm struggling on comparing this two dates.
What I have, is a class that prints a few dates and I'd need to find if one of those dates is within the past 5 minutes
HTML:
<span class="msl_info">You have responded 3 times: on 21 Sep 2018 at 10:49, 21 Sep 2018 at 10:40, 21 Sep 2018 at 10:15.</span>
JavaScript:
var m_names = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
var hour = d.getHours();
var minute = d.getMinutes();
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
//var x = document.getElementById("demo");
var hour = addZero(d.getHours());
var minute = addZero(d.getMinutes());
var minuteAgo = addZero(d.getMinutes() - 5);
//x.innerHTML = h + ":" + m;
//Today minus 5 minutes
var dateFrom = curr_date + " " + m_names[curr_month] + " " + curr_year + " at " + hour + ":" + minuteAgo;
//Now
var dateTo = curr_date + " " + m_names[curr_month] + " " + curr_year + " at " + hour + ":" + minute;
console.log(dateFrom); //21 Sep 2018 at 10:38
console.log(dateTo); // 21 Sep 2018 at 10:43
This is a fiddle
Quick example about how to solve your problem:
const e = document.getElementById('msl_info');
const dates = e.innerHTML.match(/(\d{2}\s\w{3}\s\d{4}\sat\s\d{2}:\d{2})/g);
const realDates = dates.map((date) => {
const regExp = /(\d{2}\s\w{3}\s\d{4})\sat\s(\d{2}:\d{2})/;
const parsedDate = regExp.exec(date);
return Date.parse(parsedDate[1] + ' ' + parsedDate[2]);
});
function isDateInsideInterval(date) {
const now = new Date().getTime();
const past = new Date(now - (5 * 60 * 1000)).getTime();
return date >= past && date <= now ? true : false;
}
realDates.forEach((date) => {
console.log('Is in interval: ', isDateInsideInterval(date));
});
<span id="msl_info" class="msl_info">You have responded 3 times: on 21 Sep 2018 at 14:16, 21 Sep 2018 at 10:40, 21 Sep 2018 at 14:15.</span>
I read your span content looking for dates. I transforn the dates into Date and check the interval.

Determine the calendar week for a given Date

I tried to search for "Calculating the Week for a given Date" and could not find accurate solution in a easier way. Here is what I have tried:
Let's assume the date specified is 'd'
getWeekOfDay: function(d){
var date1 = new Date(d.getFullYear(), d.getMonth(), d.getDate());
var yearWeek;
var firstMondayOfWeek1 =
this.getMondayOfWeekOneOfAGivenYear(date1.getFullYear());
var weekNumber = Math.ceil((((date1 - firstMondayOfWeek1) / 86400000) + 1) / 7);
yearWeek = date1.getFullYear() + "." + weekNumber;
if(weekNumber <= 0 ){ // Jan 01 2012;
//date falls in last week of previous year
firstMondayOfWeek1 = this.getMondayOfWeekOneOfAGivenYear(date1.getFullYear() - 1);
weekNumber = Math.ceil((((date1 - firstMondayOfWeek1) / 86400000) + 1) / 7);
yearWeek = (date1.getFullYear() - 1) + "." + weekNumber;
}
if(weekNumber === 53 ){ // Dec 29 2014; Dec 28 2020
var Dec31 = new Date(date1.getFullYear(), 11, 31);
if(Dec31.getDay() < 4){
yearWeek = (date1.getFullYear() + 1) + "." + 1;
}
}
return yearWeek;
},
getMondayOfWeekOneOfAGivenYear: function(year){
//4th Jan always falls in Week1 of that year
var fouthJan = new Date(year, 0, 4);//
var day = fouthJan.getDay();
if (fouthJan.getDay() === 0) { //Sunday
day = 7;
}
var firstMondayofW1 = new Date(fouthJan);
firstMondayofW1.setDate(firstMondayofW1.getDate() + (1 - day) * 1);
return firstMondayofW1;
},

Get x previous dates in JavaScript

I'm trying to get the past X days counting from today back using JavaScript.
However I'm only able to work out how to get today's date but now the previous dates.
Say If I wanted the last 6 days including today, it to be printed as such:
Monday Nov 5
Sunday Nov 4
Saturday Nov 3
Friday Nov 2
Thursday Nov 1
Wednesday Oct 31
Heres what I've got so far to get the current day.
(function() {
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
Date.prototype.getMonthName = function() {
return months[this.getMonth()];
};
Date.prototype.getDayName = function() {
return days[this.getDay()];
};
})();
var todayDate = new Date(),
day = todayDate.getDate(),
weekday = todayDate.getDayName(),
month = todayDate.getMonthName(),
today = weekday + ' ' + month + ' ' + day;
I guess this should work:
var msecsIn1Day = 86400000, c = 0;
var todayDate = new Date();
while(c < 6) {
var d = new Date(todayDate.getTime() - msecsIn1Day * c);
day = d.getDate(),
weekday = d.getDayName(),
month = d.getMonthName(),
today = weekday + ' ' + month + ' ' + day;
alert(today);
c++;
}
using 86400000(miliseconds) approach will have a problem with daylight savings time
suppose
var d = new Date("23/12/2012 00:00:00");
var e = new Date(d.getTime() - 86400000);
and DST is +1 then e will be 23/12/2012 01:00:00
to solve this you can have a function to calculate the date before like:
Date.prototype.getPreviousDate = function(beforeDays) {
if (!days) { beforeDays = 0 }
return new Date(new Date().setDate(this.getDate() - beforeDays));
}
then you can use it like
var todayDate = new Date(), c = 0;
while(c > 6){
var d = todayDate.getPreviousDate(c),
day = d.getDate(),
weekday = d.getDayName(),
month = d.getMonthName(),
today = weekday + ' ' + month + ' ' + day;
alert(today);
}
for more details refer to this question

Javascript date time comparison returns false but branch stmt still executed

I am confused with this Javascript behaviour. Check this code.
var NoOfMonthsElapsed = 6; //Should be >= 1 and <= 12
var MsgURL = "about:blank";
var PopupTitle = "ContactInfoUpdate";
var OptionString = "height=165,width=400,menubar=0,toolbar=0,location=1,status=0,resizable=0,status=0,HAlign=center,top=300";
var lastUpdatedDate = crmForm.all.dxb_lastcontactinfoupdatedon.DataValue; //Reads a field with date value = 01 Jan 2010
if (lastUpdatedDate)
{
var month = lastUpdatedDate.getMonth();
var year = lastUpdatedDate.getYear();
var date = lastUpdatedDate.getDate();
month = month + NoOfMonthsElapsed;
year = year + parseInt(month / 11);
month = (month % 11);
var today = new Date();
var showPopupAfterDate = new Date();
showPopupAfterDate.setYear(year);
showPopupAfterDate.setMonth(month);
var alertMsg = "LastUpdatedDate = "+ lastUpdatedDate + "\n"
var alertMsg += "Today = "+ today + "\n"
var alertMsg += "PopupAfterDate = "+ showPopupAfterDate + "\n"
var alertMsg += "Today>showPopupAfterDate = "+ (today>showPopupAfterDate) + "\n"
alert(alertMsg);
if (today>showPopupAfterDate);
{
window.open(MsgURL, PopupTitle, OptionString);
}
}
else
{
window.open(MsgURL, PopupTitle, OptionString);
}
//
// It displays the following output
//
LastUpdatedDate = Wed May 18 20:56:00 UTC+0400 2011
Today = Fri May 18 20:23:49 UTC+0400 2011
PopupAfterDate = Fri Nov 18 20:23:49 UTC+0400 2011
Today>showPopupAfterDate = false
Why today is shown as Fri May 18 2011... though May 18 2011 is Wed
Why PopupAfterDate is shown as Fri Nov 18 2011...
And Even though the dates comparission returns false; The window.open still get executed.
Your { and } are messy and you have a ; at the wrong place.
if (lastUpdatedDate) {
....
if (today>showPopupAfterDate) { // notice I removed ;
window.open(MsgURL, PopupTitle, OptionString);
}
} else {
window.open(MsgURL, PopupTitle, OptionString);
}
Your trailing semicolon closes the if statement:
if (today>showPopupAfterDate);
// --------------------------^
Found the issue:
if (today>showPopupAfterDate) //<-- remove the `;`
{
window.open(MsgURL, PopupTitle, OptionString);
}
Your code is running the if, stopping, then doing the next statement which is the window.open

Categories

Resources