Why does Javascript's Date.getDate() .setDate() behave so unpredictably? - javascript

Hobbyist coder here, and this problem is above my pay grade. I'm trying to build a dynamic html / css calendar, where the cells are filled in based on today's date. I get today's date, and then try to add days to fill in another 13 days (looping thru html elements.innerHTML).
If I try to setDate(30 + 2) and then getDate(). The code works fine. Javascript figures out that June ends at the 30th day, and the result is 2 as desired (July 2nd)
But this only works if there's only one call, if I have a loop, or call this code multiple times, then the result is different. Is there some async stuff gumming up the works? Here's code:
If you leave the "result2" call and comment the others, works great, but multiple calls, things break and numbers get repeated. Please help!
const theDate = new Date();
const todaysDate = 30;
theDate.setDate(todaysDate + 1);
let result1 = theDate.getDate();
theDate.setDate(todaysDate + 2);
let result2 = theDate.getDate();
theDate.setDate(todaysDate + 3);
let result3 = theDate.getDate();
theDate.setDate(todaysDate + 4);
let result4 = theDate.getDate();
console.log(result1);
console.log(result2);
console.log(result3);
console.log(result4);

June has 30 days but July has 31 days.
When you set the date to 32 for the first time, you are setting it to the 32nd of June and the dates after June 30 push it to July 2nd. (32-30=2)
When you set to 32 again, it is already July so the dates after July 31 push it to August 1st (32-31=1).

In answer to your question, the setDate() function is behaving so strangely for you because each time you are setting the date you are setting it relative to the previous setting, so incrementing each time by 31, 32, or 33 days instead of by 1, 2, or 3. See the brilliant answer by #Quentin for more information, this finding was entirely his and I just wanted to mention the root cause in my answer as well as my own fix to your problem.
An alternative solution if you just want to generate the dates:
const dayOfMonth = 30;
const date = new Date();
date.setDate(dayOfMonth);
console.log("Date:", date);
let timestamp = Date.parse(date);
for (let i = 1; i <= 14; i++) {
const newTimestamp = timestamp + i * (1000 * 60 * 60 * 24);
const newDate = new Date(newTimestamp);
console.log("New date:", newDate);
}
This method will manipulate the timestamp and generate new dates for each of the timestamps added to the number of milliseconds in a day.
You could use your date logic within the loop to populate the calendar as you mentioned.

If you use the Date() constructor on each iteration, you don't have to worry about the varying days of a particular month.
Details are commented in example
/**
* #desc - return a range of dates starting today (or a given
* date) and a given number of days (including start)
* #param {number} range - The number of days
* #param {string<date>} start - The date to start the range
* if not defined #default is today
* #return {array<date>} An array of dates
*/
function dayRange(range, start) {
// If undefined default is today
let now = start ? new Date(start) : new Date();
// Create an array of empty slots - .length === range
let rng = [...new Array(range)];
/*
.map() through array rng
If it's the first iteration add today's date...
... otherwise get tommorow's date...
and return it in local format
*/
return rng.map((_, i) => {
if (i === 0) {
return now.toLocaleDateString();
}
let day = now.getDate() + 1;
now.setDate(day);
return now.toLocaleDateString();
});
}
console.log("Pass the first parameter if the start day is today");
console.log(JSON.stringify(dayRange(14)));
console.log("Pass a properly formatted date string as the second parameter if you want to start on a date other than today");
console.log(JSON.stringify(dayRange(10, '05/12/2020')));

Related

JavaScript, how to create difference of date with moment.js

I am having a problem with creating an error message on a page where there is a "from date:", and a "to date:". If the difference between the two dates is greater than or equal to 60 days, I have to put up an error message.
I am trying to use moment.js and this is what my code is looking like now. It was recommended that I use it in knockout validation code. this is what it looks like right now:
var greaterThan60 = (moment().subtract('days', 60) === true) ? "The max range for from/to date is 60 days." : null;
I am still not sure how to make it greater than 60 days, not just equal to 60 days. This is what my boss gave me to help.
Reference site for moment().subtract
moment.js provides a diff() method to find difference between dates. please check below example.
var fromDate = 20180606;
var toDate = 20180406;
var dif = moment(fromDate, 'YYYYMMDD').diff(moment(toDate, 'YYYYMMDD'),'days')
console.log(dif) // 61
subtract returns a new moment object. So checking for true always returns false. You can use range and diff to calculate a diff in days and check that:
let start = moment('2016-02-27');
let end = moment('2016-03-02');
let range = moment.range(start, end);
let days = range.diff('days');
let error = null;
if (days > 60) {
error = "The max range for from/to date is 60 days.";
}
You Can try this.
var date = Date.parse("2018-04-04 00:00:00");
var selectedFromDate = new Date(date);
var todayDate = new Date();
var timedifference = Math.abs(todayDate.getTime() - selectedFromDate.getTime());
var daysDifference = Math.ceil(timedifference/(1000 * 3600 * 24));
just use if else loop for greater than 60 days validation.
if(daysDifference > 60)
{
alert("From Date should be less than 2 months");
}
Use the .isSameOrAfter function to compare if the end value is greater than or equal to the start value plus sixty days. Example:
var greaterThan60 = toDate.isSameOrAfter(startDate.add(60, 'days'));
where toDate is your end time as a moment object and startDate is the start time as a moment object. If the end date is greater than or equal to 60 days after the start date, greaterThan60 will be true.
References:
isSameOrAfter
add

How to get the calendar week difference between two moments?

I want to get the calendar week difference between two dates in javascript.
Example:
a='09-May-2018'
b='14-May-2018'
Calendar week difference between these two is 2.
I started by converting date to moment and getting the difference in terms of weeks by Moment.js diff method. But that is considering 7 days as a weeks and giving me 1 for above example.
I thought of getting the week number of moment and then subtract it. But in that, if the date is of two different year. I will get wrong result. Like '01-Jan-2017' and '01-Jan-2018' will give week number as 1.
Is there any better way to do this efficiently?
You can also calculate week difference in plain javascript. Since you haven't fully explained the rules for how to determine the number of weeks I've made some guesses. The following:
Defaults the first day of the week as Monday
Copies the dates and moves them to the start of the week
Makes sure d0 is before d1
Calculates the number of weeks as 1 + (endDate - startDate) / 7
The day for the start of the week can be set using an optional 3rd parameter: 0 = Sunday, 1 = Monday, etc.
The result is always positive. If the dates are in the same week, the difference is 1.
This only works correctly if the end date is after the start date.
/* Calculate weeks between dates
** Difference is calculated by getting date for start of week,
** getting difference, dividing and rounding, then adding 1.
** #param {Date} d0 - date for start
** #param {Date} d1 - date for end
** #param {number} [startDay] - default is 1 (Monday)
** #returns {number} weeks between dates, always positive
*/
function weeksBetweenDates(d0, d1, startDay) {
// Default start day to 1 (Monday)
if (typeof startDay != 'number') startDay = 1;
// Copy dates so don't affect originals
d0 = new Date(d0);
d1 = new Date(d1);
// Set dates to the start of the week based on startDay
[d0, d1].forEach(d => d.setDate(d.getDate() + ((startDay - d.getDay() - 7) % 7)));
// If d1 is before d0, swap them
if (d1 < d0) {
var t = d1;
d1 = d0;
d0 = t;
}
return Math.round((d1 - d0)/6.048e8) + 1;
}
console.log(weeksBetweenDates(new Date(2018, 4, 9), new Date(2018, 4, 14)));
I had a requirement that, if difference is greater that 12 weeks I have to perform some action.
So I did it by getting week by week() method of Moment. Like this:
Math.abs(endDate.diff(startDate, 'days'))<91 &&
Math.abs(startDate.week() - endDate.week()) < 12)
Using moment.js, according to https://momentjs.com/docs/#/durations/diffing/
/**
* #param fromDate - moment date
* #param toDate - moment date
* #return {int} diffInWeeks Diff between dates with weeks as unit
**/
const getDiffInWeeks = (fromDate, toDate) => {
const requestedOffset = 1
const diff = toDate.diff(fromDate);
const diffInWeeks = moment.duration(diff).as('weeks')
return Math.ceil(diffInWeeks) + requestedOffset
}

How to get current day count of the quarter [duplicate]

I have two input dates taking from Date Picker control. I have selected start date 2/2/2012 and end date 2/7/2012. I have written following code for that.
I should get result as 6 but I am getting 5.
function SetDays(invoker) {
var start = $find('<%=StartWebDatePicker.ClientID%>').get_value();
var end = $find('<%=EndWebDatePicker.ClientID%>').get_value();
var oneDay=1000 * 60 * 60 * 24;
var difference_ms = Math.abs(end.getTime() - start.getTime())
var diffValue = Math.round(difference_ms / oneDay);
}
Can anyone tell me how I can get exact difference?
http://momentjs.com/ or https://date-fns.org/
From Moment docs:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // =1
or to include the start:
a.diff(b, 'days')+1 // =2
Beats messing with timestamps and time zones manually.
Depending on your specific use case, you can either
Use a/b.startOf('day') and/or a/b.endOf('day') to force the diff to be inclusive or exclusive at the "ends" (as suggested by #kotpal in the comments).
Set third argument true to get a floating point diff which you can then Math.floor, Math.ceil or Math.round as needed.
Option 2 can also be accomplished by getting 'seconds' instead of 'days' and then dividing by 24*60*60.
If you are using moment.js you can do it easily.
var start = moment("2018-03-10", "YYYY-MM-DD");
var end = moment("2018-03-15", "YYYY-MM-DD");
//Difference in number of days
moment.duration(start.diff(end)).asDays();
//Difference in number of weeks
moment.duration(start.diff(end)).asWeeks();
If you want to find difference between a given date and current date in number of days (ignoring time), make sure to remove time from moment object of current date as below
moment().startOf('day')
To find difference between a given date and current date in number of days
var given = moment("2018-03-10", "YYYY-MM-DD");
var current = moment().startOf('day');
//Difference in number of days
moment.duration(given.diff(current)).asDays();
Try this Using moment.js (Its quite easy to compute date operations in javascript)
firstDate.diff(secondDate, 'days', false);// true|false for fraction value
Result will give you number of days in integer.
Try:
//Difference in days
var diff = Math.floor(( start - end ) / 86400000);
alert(diff);
This works for me:
const from = '2019-01-01';
const to = '2019-01-08';
Math.abs(
moment(from, 'YYYY-MM-DD')
.startOf('day')
.diff(moment(to, 'YYYY-MM-DD').startOf('day'), 'days')
) + 1
);
I made a quick re-usable function in ES6 using Moment.js.
const getDaysDiff = (start_date, end_date, date_format = 'YYYY-MM-DD') => {
const getDateAsArray = (date) => {
return moment(date.split(/\D+/), date_format);
}
return getDateAsArray(end_date).diff(getDateAsArray(start_date), 'days') + 1;
}
console.log(getDaysDiff('2019-10-01', '2019-10-30'));
console.log(getDaysDiff('2019/10/01', '2019/10/30'));
console.log(getDaysDiff('2019.10-01', '2019.10 30'));
console.log(getDaysDiff('2019 10 01', '2019 10 30'));
console.log(getDaysDiff('+++++2019!!/###10/$$01', '2019-10-30'));
console.log(getDaysDiff('2019-10-01-2019', '2019-10-30'));
console.log(getDaysDiff('10-01-2019', '10-30-2019', 'MM-DD-YYYY'));
console.log(getDaysDiff('10-01-2019', '10-30-2019'));
console.log(getDaysDiff('10-01-2019', '2019-10-30', 'MM-DD-YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
Also you can use this code: moment("yourDateHere", "YYYY-MM-DD").fromNow(). This will calculate the difference between today and your provided date.
// today
const date = new Date();
// tomorrow
const nextDay = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
// Difference in time
const Difference_In_Time = nextDay.getTime() - date.getTime();
// Difference in Days
const Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);

Javascript - unexpected behavior in dates calculations

I'm a newbie and recently started to read Beginning Javascript, by McPeak and Wilton. The authors propose an exercise about dates calculation. This is the exercise
Using the Date type, calculate the date 12 months from now.
I tried to solve it with this code
//gets today's date
var today = new Date();
//this line transforms the date in milliseconds
var daysAsMilliseconds = 1000* 60 * 60 * 24 * today.getDate();
//creates a new Date object
console.log(new Date(today.setDate(365) + daysAsMilliseconds));
The result I get here is correct(August 11th 2018).
Later, I wonder if it was really necessary to create 2 variables and tried this solution:
var today = new Date();
console.log(new Date(today.setDate(365) + (1000 * 60 * 60 * 24 * today.getDate())));
Here the solution was incorrect. The console showed August 31 2018. Why?
If necessary, here you will find the repl.it with the code
You call setDate, before you call getDate , therefore getDate will always return 365. Simply swapp it:
new Date((1000 * 60 * 60 * 24 * today.getDate()) + today.setDate(365))
Or its may easier to work with months directly:
today.setMonth(today.getMonth() + 12);
var intwelvemonths = today;
All you need to do is add 1 to the year:
var yearFromNow = new Date();
yearFromNow.setYear(yearFromNow.getFullYear() + 1);
Setting the date to 365 makes no sense; .setDate() is for day-of-month, so setting it to that constant moves the date a year (usually) from the last day of the previous month. And you don't need to do any other math outside of the date API; just increment the year, and you're done.
You're calling today.setDate(365) before you're adding the results of today.getDate(): today.getDate() will give the date that you set, not today's date.
Changing the order of operations will do the trick:
var today = new Date();
new Date((1000 * 60 * 60 * 24 * today.getDate()) + today.setDate(365));
I recommend you to use a package as moment.js because it manage a lot of date formats, and it has very good implementations for date managing.
Using moment js for add.
moment().add(Number, String);
Example
var m = moment(new Date(2011, 2, 12, 5, 0, 0));
m.hours(); // 5
m.add(1, 'days').hours(); // 5
For more docs see moment().add() docs

Add one day to date in javascript

I am sure that a lot of people asked this question but when I checked the answers it seems to me that they are wrong that what I found
var startDate = new Date(Date.parse(startdate));
//The start date is right lets say it is 'Mon Jun 30 2014 00:00:00'
var endDate = new Date(startDate.getDate() + 1);
// the enddate in the console will be 'Wed Dec 31 1969 18:00:00' and that's wrong it should be 1 july
I know that .getDate() return from 1-31 but Does the browser or the javascript increase only the day without updating the month and the year ?
and in this case Should I write an algorithm to handle this ? or there is another way ?
Note that Date.getDate only returns the day of the month. You can add a day by calling Date.setDate and appending 1.
// Create new Date instance
var date = new Date()
// Add a day
date.setDate(date.getDate() + 1)
JavaScript will automatically update the month and year for you.
EDIT:
Here's a link to a page where you can find all the cool stuff about the built-in Date object, and see what's possible: Date.
The Date constructor that takes a single number is expecting the number of milliseconds since December 31st, 1969.
Date.getDate() returns the day index for the current date object. In your example, the day is 30. The final expression is 31, therefore it's returning 31 milliseconds after December 31st, 1969.
A simple solution using your existing approach is to use Date.getTime() instead. Then, add a days worth of milliseconds instead of 1.
For example,
var dateString = 'Mon Jun 30 2014 00:00:00';
var startDate = new Date(dateString);
// seconds * minutes * hours * milliseconds = 1 day
var day = 60 * 60 * 24 * 1000;
var endDate = new Date(startDate.getTime() + day);
JSFiddle
Please note that this solution doesn't handle edge cases related to daylight savings, leap years, etc. It is always a more cost effective approach to instead, use a mature open source library like moment.js to handle everything.
There is issue of 31st and 28th Feb with getDate() I use this function getTime and 24*60*60*1000 = 86400000
Use this function:
function incrementDate(dateInput,increment) {
var dateFormatTotime = new Date(dateInput);
var increasedDate = new Date(dateFormatTotime.getTime() +(increment *86400000));
return increasedDate;
}
Example as below:
var dateWith31 = new Date("2017-08-31");
var dateWith29 = new Date("2016-02-29");
var amountToIncreaseWith = 1; //Edit this number to required input
console.log(incrementDate(dateWith31,amountToIncreaseWith));
console.log(incrementDate(dateWith29,amountToIncreaseWith));
function incrementDate(dateInput,increment) {
var dateFormatTotime = new Date(dateInput);
var increasedDate = new Date(dateFormatTotime.getTime() +(increment *86400000));
return increasedDate;
}
use this i think it is useful for you
var endDate=startDate.setDate(startDate.getDate() + 1);
I think what you are looking for is:
startDate.setDate(startDate.getDate() + 1);
Also, you can have a look at Moment.js
A javascript date library for parsing, validating, manipulating, and formatting dates.
var datatoday = new Date();
var datatodays = datatoday.setDate(new Date(datatoday).getDate() + 1);
todate = new Date(datatodays);
console.log(todate);
This will help you...
add one day in javascript in one line
NB: if you want to add a specific number of days ... just replace 1 with the number of days you want
new Date(new Date().setDate(new Date().getDate() + 1))
console.log(new Date(new Date().setDate(new Date().getDate() + 1)))
i know it's been long time since this is posted but here's my answer
function addDays(date, n)
{
const oneDayInMs = 86400 * 1000;
return new Date(Date.parse(date) + (n * oneDayInMs));
}
addDays(new Date(), 1);
Just for the sake of adding functions to the Date prototype:
In a mutable fashion / style:
Date.prototype.addDays = function(n) {
this.setDate(this.getDate() + n);
};
// Can call it tomorrow if you want
Date.prototype.nextDay = function() {
this.addDays(1);
};
Date.prototype.addMonths = function(n) {
this.setMonth(this.getMonth() + n);
};
Date.prototype.addYears = function(n) {
this.setFullYear(this.getFullYear() + n);
}
// etc...
var currentDate = new Date();
currentDate.nextDay();
If you don't mind using a library, DateJS (https://github.com/abritinthebay/datejs/) would make this fairly easy. You would probably be better off with one of the answers using vanilla JavaScript however, unless you're going to take advantage of some other DateJS features like parsing of unusually-formatted dates.
If you're using DateJS a line like this should do the trick:
Date.parse(startdate).add(1).days();
You could also use MomentJS which has similar features (http://momentjs.com/), however I'm not as familiar with it.
The below will add a single day to a current time. I believe this will handle daylight saving times, etc.
function increment_date (date) {
let old_date = new Date (date);
date.setDate (old_date.getDate() + 1);
while (date.getDate() == old_date.getDate()) {
date.setHours (date.getHours() + 1);
}
date.setHours (0);
}

Categories

Resources