Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add weeks to date using javascript?

Javascript definitely isn't my strongest point. I've been attempting this for a couple of hours now and seem to be getting stuck with date formatting somewhere.

I have a form where a user selected a date (dd/mm/yyyy) and then this date will be taken and 2 weeks will be added to it and then date will be copied to another form field.

My latest attempt below isn't even adding a date yet just copying the selected date in one form field to another, if I select '03/02/2012', it outputs 'Fri Mar 02 2012 00:00:00 GMT+0000 (GMT Standard Time)', so its outputting in American format as well as the full date. How to I get it to out put in the same format and add 2 weeks?

function LicenceToOccupy(acceptCompletionDate) {     var date1 = new Date(acceptCompletionDate);     document.frmAccept.acceptLicence.value = date1;  } 
like image 524
Jammer Avatar asked Jul 05 '12 12:07

Jammer


People also ask

How do you add weeks to a date in typescript?

function addWeeks(numOfWeeks, date = new Date()) { date. setDate(date. getDate() + numOfWeeks * 7); return date; } // Add 2 weeks to current Date console.

How would you change the date to one week later in Javascript?

You can do this : let numWeeks = 2; let now = new Date(); now. setDate(now. getDate() + numWeeks * 7); alert(now);

How do you add a week to a date by moment?

This is a pretty robust function for adding time to an existing moment. To add time, pass the key of what time you want to add, and the amount you want to add. moment(). add(7, 'days');


1 Answers

You can do this :

let numWeeks = 2; let now = new Date(); now.setDate(now.getDate() + numWeeks * 7); alert(now); 

You can see the fiddle here.

According to the documentation in MDN

The setDate() method sets the day of the Date object relative to the beginning of the currently set month.

like image 194
Arvind Sridharan Avatar answered Oct 07 '22 01:10

Arvind Sridharan