How To add number of month into the given date in javascript? - 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.

Related

How can I show the days of last week in javascript?

I need a script that show the days of the last week, until today.
But when it's early in the month, like on day 4, my code has this problem.
I'm using getDate(). Is there a function that can help me?
result
You can use getDate(), but don't put it in a variable that you then just decrement with the risk of going to 0 and below.
Instead use setDate() (potentially in combination with getDate()) to decrement your date object day by day, and then read out the date in the format you want:
var dt = new Date();
headers = ['Hoje'];
for (var i = 1; i < 7; i++) {
dt.setDate(dt.getDate() - 1);
headers.push(dt.toLocaleDateString('pt-PT').substr(0,5));
}
console.log(headers);
To go back a week from today, regardless of where in the month you are (even within seven days from the beginning of the month), just .setDate() to a value that is seven (days) less than what .getDate() gives:
var d = new Date()
d.toDateString()
"Thu May 04 2017"
// go back a week
d.setDate(d.getDate() - 7);
1493321406767
// prove that it worked
d.toDateString()
"Thu Apr 27 2017"
You can use getDay method which gives the day of the week (1-monday, 3-wednesday). From this value you can put a decreasing loop till 1-monday or 0-sunday to show previous day of week.
var weekdays = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
var d = new Date();
var currDay = d.getDay();
var currDate = d.getDate();
var str = "";
for(var count=currDay; count>=0 && currDate >= 1; count--, currDate--){
str += currDate +" "+weekdays[count] + ", ";
}
console.log(str);
Today's output: 5 Fri, 4 Thu, 3 Wed, 2 Tue, 1 Mon

Invalid date being returned

using Mirth Connect.
I'm trying to get the current date and add 2 days to it.
it is currently 8:10am Eastern Time 3/24/2016
var startDate
var currentDay = DateUtil.getCurrentDate('F');
var currentDate = new Date(DateUtil.getCurrentDate('yyyy-MM-dd'));
logger.info("Current: " + currentDate);
currentDate.setDate(currentDate.getDate()+2);
startDate = DateUtil.formatDate('yyyy-MM-dd', currentDate);
logger.info("+2: " + startDate);
I get this in return
[2016-03-24 08:10:09,694] INFO (db-connector:?): Current: Wed Mar 23 2016 20:00:00 GMT-0400 (EDT) - It's not wednesday nor is the time correct
[2016-03-24 08:10:09,694] INFO (db-connector:?): +2: 2016-03-25
- This should display Saturdays 2016-03-26 since i'm adding +2 days to the current time.
var currentDay = DateUtil.getCurrentDate('F'); however returns 4 so it is thursday.
I have switched to the following which solved my issue.
var currentDTTM = new java.util.Calendar.getInstance();
currentDTTM.add(java.util.Calendar.DATE, 2);
var strCurrentDTTM = new java.text.SimpleDateFormat("yyyy-MM-dd").format(currentDTTM.getTime());

Add A Year To Today's Date

I am trying to add a year to todays date. I am working in a system that does not allow you to use standard JavaScript.
For instance, to get todays date I have to use:
javascript:now();
I have tried:
javascript:now(+1);
I have never seen this before, but am in need of adding one year to todays date...
Has anyone seen getting current date this way before? And if so, how could I add a year?
Use the Date.prototype.setFullYear method to set the year to what you want it to be.
For example:
const aYearFromNow = new Date();
aYearFromNow.setFullYear(aYearFromNow.getFullYear() + 1);
console.log(aYearFromNow);
There really isn't another way to work with dates in JavaScript if these methods aren't present in the environment you are working with.
You can create a new date object with todays date using the following code:
var d = new Date();
console.log(d);
// => Sun Oct 11 2015 14:46:51 GMT-0700 (PDT)
If you want to create a date a specific time, you can pass the new Date constructor arguments
var d = new Date(2014);
console.log(d)
// => Wed Dec 31 1969 16:00:02 GMT-0800 (PST)
If you want to take todays date and add a year, you can first create a date object, access the relevant properties, and then use them to create a new date object
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
var day = d.getDate();
var c = new Date(year + 1, month, day);
console.log(c);
// => Tue Oct 11 2016 00:00:00 GMT-0700 (PDT)
You can read more about the methods on the date object on MDN
Date Object
One liner as suggested here
How to determine one year from now in Javascript
by JP DeVries
new Date(new Date().setFullYear(new Date().getFullYear() + 1))
Or you can get the number of years from somewhere in a variable:
const nr_years = 3;
new Date(new Date().setFullYear(new Date().getFullYear() + nr_years))
This code adds the amount of years required for a date.
var d = new Date();
// => Tue Oct 01 2017 00:00:00 GMT-0700 (PDT)
var amountOfYearsRequired = 2;
d.setFullYear(d.getFullYear() + amountOfYearsRequired);
// => Tue Oct 01 2019 00:00:00 GMT-0700 (PDT)
I like to keep it in a single line, you can use a self calling function for this eg:
If you want to get the timestamp of +1 year in a single line
console.log(
(d => d.setFullYear(d.getFullYear() + 1))(new Date)
)
If you want to get Date object with single line
console.log(
(d => new Date(d.getFullYear() + 1, d.getMonth(), d.getDate()))(new Date)
)
In Angular, This is how you Calculate Date
today = new Date();
year = this.today.getFullYear();
month = this.today.getMonth();
day = this.today.getDate();
//To go 18 years back
yearsBack18= new Date(this.year - 18, this.month, this.day);
//To go to same day next year
nextYear= new Date(this.year + 1, this.month, this.day);
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
var day = d.getDate();
var fulldate = new Date(year + 1, month, day);
var toDate = fulldate.toISOString().slice(0, 10);
$("#txtToDate").val(toDate);
output : 2020-01-02
//This piece of code will handle the leap year addition as well.
function updateExpiryDate(controlID, value) {
if ( $("#ICMEffectiveDate").val() != '' &&
$("#ICMTermYears").val() != '') {
var effectiveDate = $("#ICMEffectiveDate").val();
var date = new Date(effectiveDate);
var termYears = $("#ICMTermYears").val();
date = new Date(date.setYear(date.getFullYear() + parseInt(termYears)));
var expiryDate = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
$('#ICMExpiryDate').val(expiryDate);
}
}
var yearsToAdd = 5;
var current = new Date().toISOString().split('T')[0];
var addedYears = Number(this.minDate.split('-')[0]) + yearsToAdd + '-12-31';

How can I add 1 day to current date?

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');

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

Categories

Resources