How can I add 1 day to current date? - javascript

I have a current Date object that needs to be incremented by one day using the JavaScript Date object. I have the following code in place:
var ds = stringFormat("{day} {date} {month} {year}", {
day: companyname.i18n.translate("day", language)[date.getUTCDay()],
date: date.getUTCDate(),
month: companyname.i18n.translate("month", language)[date.getUTCMonth()],
year: date.getUTCFullYear()
});
How can I add one day to it?
I've added +1 to getUTCDay() and getUTCDate() but it doesn't display 'Sunday'
for day, which I am expecting to happen.

To add one day to a date object:
var date = new Date();
// add a day
date.setDate(date.getDate() + 1);

In my humble opinion the best way is to just add a full day in milliseconds, depending on how you factor your code it can mess up if you are on the last day of the month.
For example Feb 28 or march 31.
Here is an example of how I would do it:
var current = new Date(); //'Mar 11 2015' current.getTime() = 1426060964567
var followingDay = new Date(current.getTime() + 86400000); // + 1 day in ms
followingDay.toLocaleDateString();
Imho this insures accuracy
Here is another example. I do not like that. It can work for you but not as clean as example above.
var today = new Date('12/31/2015');
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate()+1);
tomorrow.toLocaleDateString();
Imho this === 'POOP'
So some of you have had gripes about my millisecond approach because of day light savings time. So I'm going to bash this out. First, Some countries and states do not have Day light savings time. Second Adding exactly 24 hours is a full day. If the date number does not change once a year but then gets fixed 6 months later I don't see a problem there. But for the purpose of being definite and having to deal with allot the evil Date() I have thought this through and now thoroughly hate Date. So this is my new Approach.
var dd = new Date(); // or any date and time you care about
var dateArray = dd.toISOString().split('T')[0].split('-').concat( dd.toISOString().split('T')[1].split(':') );
// ["2016", "07", "04", "00", "17", "58.849Z"] at Z
Now for the fun part!
var date = {
day: dateArray[2],
month: dateArray[1],
year: dateArray[0],
hour: dateArray[3],
minutes: dateArray[4],
seconds:dateArray[5].split('.')[0],
milliseconds: dateArray[5].split('.')[1].replace('Z','')
}
Now we have our Official Valid international Date Object clearly written out at Zulu meridian.
Now to change the date
dd.setDate(dd.getDate()+1); // this gives you one full calendar date forward
tomorrow.setDate(dd.getTime() + 86400000);// this gives your 24 hours into the future. do what you want with it.

If you want add a day (24 hours) to current datetime you can add milliseconds like this:
new Date(Date.now() + ( 3600 * 1000 * 24))

int days = 1;
var newDate = new Date(Date.now() + days*24*60*60*1000);
CodePen
var days = 2;
var newDate = new Date(Date.now()+days*24*60*60*1000);
document.write('Today: <em>');
document.write(new Date());
document.write('</em><br/> New: <strong>');
document.write(newDate);

Inspired by jpmottin in this question, here's the one line code:
var dateStr = '2019-01-01';
var days = 1;
var result = new Date(new Date(dateStr).setDate(new Date(dateStr).getDate() + days));
document.write('Date: ', result); // Wed Jan 02 2019 09:00:00 GMT+0900 (Japan Standard Time)
document.write('<br />');
document.write('Trimmed Date: ', result.toISOString().substr(0, 10)); // 2019-01-02
Hope this helps

simply you can do this
var date = new Date();
date.setDate(date.getDate() + 1);
console.log(date);
now the date will be the date of tomorrow. here you can add or deduct the number of days as you wish.

This is function you can use to add a given day to a current date in javascript.
function addDayToCurrentDate(days){
let currentDate = new Date()
return new Date(currentDate.setDate(currentDate.getDate() + days))
}
// current date = Sun Oct 02 2021 13:07:46 GMT+0200 (South Africa Standard Time)
// days = 2
console.log(addDayToCurrentDate(2))
// Mon Oct 04 2021 13:08:18 GMT+0200 (South Africa Standard Time)

// Function gets date and count days to add to passed date
function addDays(dateTime, count_days = 0){
return new Date(new Date(dateTime).setDate(dateTime.getDate() + count_days));
}
// Create some date
const today = new Date("2022-02-19T00:00:00Z");
// Add some days to date
const tomorrow = addDays(today, 1);
// Result
console.log("Tomorrow => ", new Date(tomorrow).toISOString());
// 2022-02-20T00:00:00.000Z

We can get date of the day after today by using timedelta with numOfDays specified as 1 below.
from datetime import date, timedelta
tomorrow = date.today() + timedelta(days=1)

currentDay = '2019-12-06';
currentDay = new Date(currentDay).add(Date.DAY, +1).format('Y-m-d');

Related

Create random UNIX timestamp based on if-else clause

How do I create a random UNIX timestamp using JavaScript:
Between now and the end of the working day (i.e. today between 08:00-17:00) if appointment.status === "today".
From tomorrow + 1 week but keeping in mind the working day (so it can be next week Tuesday 13:00, keeping in mind the working day i.e. 08:00-17:00) if appointment.status === "pending".
This is what I have done so far:
if(appointment.status === "today") {
appointment.timestamp = (function() {
return a
})();
} else if(appointment.status === "pending") {
appointment.timestamp = (function() {
return a
})();
}
This is similar to another question (Generate random date between two dates and times in Javascript) but to handle the "pending" appointments you'll also need a way to get a day between tomorrow and a week from tomorrow.
This function will return a random timestamp between 8:00 and 17:00 on the date that is passed to it:
var randomTimeInWorkday = function(date) {
var begin = date;
var end = new Date(begin.getTime());
begin.setHours(8,0,0,0);
end.setHours(17,0,0,0);
return Math.random() * (end.getTime() - begin.getTime()) + begin.getTime();
}
To get a random timestamp today between 08:00 and 17:00 today you could do:
var today = new Date();
var timestamp = randomTimeInWorkday(today);
console.log(timestamp); // 1457033914204.1597
console.log(new Date(timestamp)); // Thu Mar 03 2016 14:38:34 GMT-0500 (EST)
This function will return a random date between tomorrow and a week from tomorrow for the date that is passed to it:
var randomDayStartingTomorrow = function(date) {
var begin = new Date(date.getTime() + 24 * 60 * 60 * 1000);
var end = new Date(begin.getTime());
end.setDate(end.getDate() + 7);
return new Date(Math.random() * (end.getTime() - begin.getTime()) + begin.getTime());
}
To get a random timestamp between 08:00 and 17:00 on a random day between tomorrow and a week from tomorrow, you could do:
var today = new Date();
var randomDay = randomDayStartingTomorrow(today);
var timestamp = randomTimeInWorkday(randomDay);
console.log(timestamp); // 1457194668335.3162
console.log(new Date(timestamp)); // Sat Mar 05 2016 11:17:48 GMT-0500 (EST)

How To add number of month into the given date in javascript?

I want to add month into the select date by the user.
startdate=document.getElementById("jscal_field_coverstartdate").value;
now I want to add 11 month from the above startdate. How to do that.
date format = 2013-12-01
Without the date format it is difficult to tell, however you can try like this
add11Months = function (date) {
var splitDate = date.split("-");
var newDate = new Date(splitDate[0], splitDate[1] - 1, splitDate[2]);
newDate.setMonth(newDate.getMonth() + 11);
splitDate[2] = newDate.getDate();
splitDate[1] = newDate.getMonth() + 1;
splitDate[0] = newDate.getFullYear();
return startdate = splitDate.join("-");
}
var startdate = add11Months("2013-12-01");
alert(startdate)
JSFiddle
If your startdate is in correct date format you can try using moment.js or Date object in javascript.
In Javascript, it can be achieved as follow:
var date = new Date("2013-12-01");
console.log(date);
//output: Sun Dec 01 2013 05:30:00 GMT+0530 (India Standard Time)
var newdate = date.setDate(date.getDate()+(11*30));
console.log(new Date(newdate));
// output: Mon Oct 27 2014 05:30:00 GMT+0530 (India Standard Time)
In above lines, I have used 30 days per month as default. So you will get exact 11 month but little deviation in date. Is this what you want ? You can play around this likewise. I hope it help :)
For more about Date you can visit to MDN.
You can do it like this:
var noOfMonths = 11
var startdate = document.getElementById("jscal_field_coverstartdate").value;
startdate.setMonth(startdate.getMonth() + noOfMonths)
Try this:
baseDate.setMonth(2);
baseDate.setDate(30);
noMonths = 11;
var sum = new Date(new Date(baseDate.getTime()).setMonth(baseDate.getMonth() + noMonths);
if (sum.getDate() < baseDate.getDate()) { sum.setDate(0); }
var m = newDate.getDate();
var d = newDate.getMonth() + 1;
var yyyy = newDate.getFullYear();
return (yyyy+"-"+m+"-"+d);
Notes:
Adding months (like adding one month to January 31st) can overflow the days field and cause the month to increment (in this case you get a date in March). If you want to add months and then overflow the date then .setMonth(base_date.getMonth()+noMonths) works but that's rarely what people think of when they talk about incrementing months.
It handles cases where 29, 30 or 31 turned into 1, 2, or 3 by eliminating the overflow
Day of Month is NOT zero-indexed so .setDate(0) is last day of prior month.

Javascript adding days to a Date

Hi I am trying to create a variable today that is the current date today. I am trying to add 106 days to it which works successfully. Then I am trying to create a second variable today2 and subtract 31 days from the 'today' variable (current date + 106 -31). This part is not working. This is what it is giving me...
Thu Mar 28 11:52:21 EDT 2013
Tue Nov 27 11:52:21 EST 2012
The second line is not 31 days before the first line. Can someone help me correct this?
Feel free to play with my jsfiddle http://jsfiddle.net/fjhxW/
<div id="current"></div>
<div id="current2"></div>
<div id="current3"></div>
var today = new Date();
var today2 = new Date();
today.setDate(today.getDate() + 106);
today2.setDate(today.getDate() - 31);
var dd = today.getDate();
var mm = today.getMonth(); //January is 0!
var yy = today.getFullYear();
document.getElementById('current').innerHTML = today;
document.getElementById('current2').innerHTML = today2;
it's Xmas time so I give the answer just to copy/paste:
var oneDay = 24 * 60 * 60 * 1000, // 24h
today = new Date().getTime(), // in ms
firstDate,
secondDate;
firstDate = new Date(today + 106 * oneDay);
secondDate = new Date(firstDate.getTime() - 31 * oneDay);
try datejs:
Date.parse('t - 31 d'); // today - 31 days
Date.today().add(106).days().add(-31).days();
You cannot pass a negative number to setDate. setDate is used to set the date to set the absolute day, not relative days.
From the docs:
If the parameter you specify is outside of the expected range, setDate attempts to update the date information in the Date object accordingly. For example, if you use 0 for dayValue, the date will be set to the last day of the previous month.
A mathemathical solution:
Add 75 days to your current day (106 - 31), then add 31 days to that date. Change the order in what you are showing both dates on your code.
Why go forward and backward when you can always go forward?

How to find the next 4 days from the current day using javascript

I found the current day as Mar 27 2012 ....
var currentday = currentday.format("mmm d yyyy");
I want to find the add three days with this value.
i.e. i need the output as Mar 30 2012.
I also need to find the starting and ending date of a calendar. i.e. Feb 26 2012 - Mar 31 2012 to display the current month as displaying in calendar month view.
Can any one help me on this please....
var currentday = new Date();
var nextDay = new Date();
nextDay.setDate(currentday.getDate() + 4);
//Set number of days you want to compute to
var days=4;
//Get current date or whatever date you want to compute from
var currentDate=new Date();
var nDaysFromNow=new Date();
nDaysFromNow.setDate(currentDate.getDate()+days);
You can add days using the getDate() function like so:
var someDate = new Date();
someDate = someDate.getDate() + 3;
See code below.. Hope it helps
var days = 4;
var next = new Date((new Date).getTime() + ((1000*3600*24) *days));

Concatenate a date and time value

i need to concatenate a date value and a time value to make one value representing a datetime in javascript.
thanks,
daniel
Working with strings is fun and all, but let's suppose you have two datetimes and don't like relying on strings.
function combineDateWithTime(d, t)
{
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
t.getHours(),
t.getMinutes(),
t.getSeconds(),
t.getMilliseconds()
);
}
Test:
var taxDay = new Date(2016, 3, 15); // months are 0-indexed but years and dates aren't.
var clockout = new Date(0001, 0, 1, 17);
var timeToDoTaxes = combineDateWithTime(taxDay, clockout);
// yields: Fri Apr 15 2016 17:00:00 GMT-0700 (Pacific Daylight Time)
I could not make the accepted answer work so used moment.js
date = moment(selected_date + ' ' + selected_time, "YYYY-MM-DD HH:mm");
date._i "11-06-2014 13:30"
Assuming "date" is the date string and "time" is the time string:
// create Date object from valid string inputs
var datetime = new Date(date+' '+time);
// format the output
var month = datetime.getMonth()+1;
var day = datetime.getDate();
var year = datetime.getFullYear();
var hour = this.getHours();
if (hour < 10)
hour = "0"+hour;
var min = this.getMinutes();
if (min < 10)
min = "0"+min;
var sec = this.getSeconds();
if (sec < 10)
sec = "0"+sec;
// put it all togeter
var dateTimeString = month+'/'+day+'/'+year+' '+hour+':'+min+':'+sec;
Depending on the type of the original date and time value there are some different ways to approach this.
A Date object (which has both date and time) may be created in a number of ways.
birthday = new Date("December 17, 1995 03:24:00");
birthday = new Date(1995,11,17);
birthday = new Date(1995,11,17,3,24,0);
If the original date and time also is objects of type Date, you may use getHours(), getMinutes(), and so on to extract the desired values.
For more information, see Mozilla Developer Center for the Date object.
If you provide more detailed information in your question I may edit the answer to be more specific.

Categories

Resources