Error incrementing days to a specific date - javascript

I'm trying to increment one day to a given date. My code, inspired by this answer, looks like:
var date = getDateFromUIControl();
var backupDate = new Date();
backupDate.setDate(date.getDate() + 1);
However, I'm seeing a strange behaviour. Today is December 5th, 2019. If the user selects January 1, 2020 (stored in date variable), then backupDate ends up being January 2nd, 2019, instead of 2020. What is wrong with this code? How should I go about incrementing the date, if what I'm doing is wrong?
Note: because of whatever policies my company has, I can't use any JavaScript library other than jQuery.

new Date() returns the current Date(example: 05/12/2019). You are just changing the date alone in current date. Still the year is 2019.
it should be like,
date.setDate(date.getDate() + 1);
if you can't change the original date object, then it can be done like this,
var changedDate = new Date(date);
changedDate.setDate(changedDate.getDate() + 1);

var date = getDateFromUIControl();
var backupDate = new Date();
backupDate.setDate(new Date(date).getDate() + 1);

nextDay is one day after date:
var date = getDateFromUIControl();
var nextDay = new Date(date.getYear(), date.getMonth(), date.getDate()+1);
Also you don't need to worry about overflowing d.getDate()+1 (e.g. 31+1) - the Date constructor is smart enough to go into the next month.

Related

Checking if date is greater than today

Trying out a Jquery to confirm if date selected is equal to today or greater than.
If i select today, it return it as the day selected is less than today. Selecting previous day works well but selecting today returns less than. Any tip.
var firstRepaymentDate = new Date($('#First_Repayment_Date').val());
var today = new Date();
if (firstRepaymentDate.getTime() < today.getTime()) {
alert('The First Repayment Date Can only Be Today Or Future Date');
return false;
}
Don't forget that new Date() will include the current time as well. You'll need to remove that time component with today.setHours(0,0,0,0) for the comparison to be correct.
Also, setHours() returns the underlying value like getTime() so you can do
var firstRepaymentDate = new Date($('#First_Repayment_Date').val());
var today = new Date();
if (firstRepaymentDate.getTime() < today.setHours(0,0,0,0)) {
alert('The First Repayment Date Can only Be Today Or Future Date');
return false;
}
In response to the comment about adding 20 days:
This is a little more detailed but is fairly easy.
var today = new Date();
var plus20Days = new Date(today.setDate(today.getDate() + 20));
again you can then use setHours() to reset the time component.
new Date() considers time too, not only the date. I think the easiest way to achieve this is to compare years, months and days by using respectively getFullYear() , getMonth() , getDate().
Check all the methods that manipulate js Date here
https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Date

React Native new Date() not working

I tried to get Date from datestring but it's not wokring properly.
var time = new Date('2017-12-26T02:12:00')
But when I called time.getHours() it returns 12.
I am not sure what I am doing wrong.
Use below code to get day, month and year.
var date = new Date(),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear(),
today = day+"-"+month+"-"+year;
You can change the format of date as per your requirement.
Adding below code fixed the problem
time.setMinutes(time.getMinutes() + time.getTimezoneOffset());
:)

Get the most recently occurring Sunday

I need to display the current week in a calendar view, starting from Sunday.
What's the safest way to determine "last sunday" in Javascript?
I was calculating it using the following code:
Date.prototype.addDays = function(n) {
return new Date(this.getTime() + (24*60*60*1000)*n);
}
var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var lastSunday = today.addDays(0-today.getDay());
This code makes the assumption that every day consists of twenty four hours. This is correct, EXCEPT if it's a daylight savings crossover day, in which case the day could be twenty-three or twenty-five hours.
This week, In Sydney, Australia, we set our clocks forward an hour. As a result, my code calculates lastSunday as 23:00 on Saturday.
So what IS the safest and most efficient way to determine last Sunday?
To safely add exactly one day, use:
d.setDate(d.getDate() + 1);
which is daylight saving safe. To set a date object to the last Sunday:
function setToLastSunday(d) {
return d.setDate(d.getDate() - d.getDay());
}
Or to return a new Date object for last Sunday:
function getLastSunday(d) {
var t = new Date(d);
t.setDate(t.getDate() - t.getDay());
return t;
}
Edit
The original answer had an incorrect version adding time, that does add one day but not how the OP wants.
Try this jsfiddle
It uses only built in date methods
var now = new Date();
var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var lastSunday = new Date(today.setDate(today.getDate()-today.getDay()));
using date-fn library: previousSunday(date)
const now = new Date(); // the date to start counting from
previousSunday(now);
Docs: https://date-fns.org/v2.25.0/docs/previousSunday

next day of a date in javascript with default js functions

Is it possible to get next date of a given date in "yyyymmdd" format with default java script or jquery functions?
As you've specified jQuery UI you can use its built-in date formatter to get the required output.
The use of the regexp and new Date shown below is to guarantee that the vagaries of date parsing don't affect the result.
function getTomorrow(dateStr) {
var ymd = dateStr.match(/^(\d{4})(\d{2})(\d{2})$/);
if (ymd) {
var date = new Date(ymd[1], ymd[2] - 1, ymd[3]);
date.setDate(date.getDate() + 1);
return $.datepicker.formatDate('yymmdd', date);
} else { // parse error
return null;
}
}
Demo at http://jsfiddle.net/alnitak/R8awH/
There seems to be a bit of confusion here.
At the heart of a javascript Date object is the milliseconds since 1970-01-01 00:00:00 UTC. That last bit is very important.
If you create a date by specifying the parts, e.g. for 2 September 2012 (note month number):
new Date(2012, 8, 2);
then a date object is created for midnight at the start of the date in the local time zone of the host, i.e. 2012-09-02T00:00:00 in the local timezone. However, if you specify a time since epoch, e.g.
new Date(1346544000000) // 2012-09-02T00:00:00Z
then the date is created at that time UTC, so it will show a different local time in different timezones that represents the same time UTC. So if the time is 2012-09-02T00:00:00Z, then in a timezone ten hours ahead of GMT (GMT+10) it will be:
2012-09-02T10:00:00+1000
If the timezone is six hours behind GMT (GMT-06) it will be:
2012-09-01T18:00:00-0600
and so on.
Construct the date object, and set the date plus 1.
var dateStr = "20120902";
var d = new Date(dateStr.replace(/(\d{4})(\d{2})(\d{2})/, '$1/$2/$3'));
d.setDate(d.getDate() + 1);
console.log(d);
Here is your code:
function getnextDay(prevDate) {
var weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
prevDate = prevDate.toString();
var formatteDate = prevDate.substr(0, 4) + ',' + prevDate.substr(4, 2) + ',' + prevDate.substr(6, 2);
formatteDate = new Date(formatteDate);
document.write(weekday[formatteDate.getDay() + 1])
}
getnextDay(19890831)​​
and
FIDDLE
Its pretty straight forward.
var today = new Date();
var date = new Date(today.getFullYear(),today.getMonth(),today.getDate()+1);
Use moment.js if you extensively use date functionalities.
For just getting the next day, this would suffice.
yes
It is pretty much easy with javaScript as follow:
today = new Date().getTime();
tomorrow = today + 24*60*60*1000;
parsed_tomorrow = new Date(tomorrow);

Simple javascript date math... not really

I am trying to create a simple script that gives me the next recycling date based on a biweekly schedule starting on Wed Jul 6, 2011. So I've created this simple function...
function getNextDate(startDate) {
if (today <= startDate) {
return startDate;
}
// calculate the day since the start date.
var totalDays = Math.ceil((today.getTime()-startDate.getTime())/(one_day));
// check to see if this day falls on a recycle day
var bumpDays = totalDays%14; // mod 14 -- pickup up every 14 days...
// pickup is today
if (bumpDays == 0) {
return today;
}
// return the closest day which is in 14 days, less the # of days since the last
// pick up..
var ms = today.getTime() + ((14- bumpDays) * one_day);
return new Date(ms);
}
and can call it like...
var today=new Date();
var one_day=1000*60*60*24; // one day in milliseconds
var nextDate = getNextDate(new Date(2011,06,06));
so far so good... but when I project "today" to 10/27/2011, I get Tuesday 11/8/2011 as the next date instead of Wednesday 11/9/2011... In fact every day from now thru 10/26/2011 projects the correct pick-up... and every date from 10/27/2011 thru 2/28/2012 projects the Tuesday and not the Wednesday. And then every date from 2/29/2012 (leap year) thru 10/24/2012 (hmmm October again) projects the Wednesday correctly. What am I missing? Any help would be greatly appreciated..
V
The easiest way to do this is update the Date object using setDate. As the comments for this answer indicate this isn't officially part of the spec, but it is supported on all major browsers.
You should NEVER update a different Date object than the one you did the original getDate call on.
Sample implementation:
var incrementDate = function (date, amount) {
var tmpDate = new Date(date);
tmpDate.setDate(tmpDate.getDate() + amount)
return tmpDate;
};
If you're trying to increment a date, please use this function. It will accept both positive and negative values. It also guarantees that the used date objects isn't changed. This should prevent any error which can occur if you don't expect the update to change the value of the object.
Incorrect usage:
var startDate = new Date('2013-11-01T11:00:00');
var a = new Date();
a.setDate(startDate.getDate() + 14)
This will update the "date" value for startDate with 14 days based on the value of a. Because the value of a is not the same is the previously defined startDate it's possible to get a wrong value.
Expanding on Exellian's answer, if you want to calculate any period in the future (in my case, for the next pay date), you can do a simple loop:
var today = new Date();
var basePayDate = new Date(2012, 9, 23, 0, 0, 0, 0);
while (basePayDate < today) {
basePayDate.setDate(basePayDate.getDate()+14);
}
var nextPayDate = new Date(basePayDate.getTime());
basePayDate.setDate(nextPayDate.getDate()-14);
document.writeln("<p>Previous pay Date: " + basePayDate.toString());
document.writeln("<p>Current Date: " + today.toString());
document.writeln("<p>Next pay Date: " + nextPayDate.toString());
This won't hit odd problems, assuming the core date services work as expected. I have to admit, I didn't test it out to many years into the future...
Note: I had a similar issue; I wanted to create an array of dates on a weekly basis, ie., start date 10/23/2011 and go for 12 weeks. My code was more or less this:
var myDate = new Date(Date.parse(document.eventForm.startDate.value));
var toDate = new Date(myDate);
var week = 60 * 60 * 24 * 7 * 1000;
var milliseconds = toDate.getTime();
dateArray[0] = myDate.format('m/d/Y');
for (var count = 1; count < numberOccurrences; count++) {
milliseconds += week;
toDate.setTime(milliseconds);
dateArray[count] = toDate.format('m/d/Y');
}
Because I didn't specify the time and I live in the US, my default time was midnight, so when I crossed the daylight savings time border, I moved into the previous day. Yuck. I resolved it by setting my time of day to noon before I did my week calculation.

Categories