0

I have two textboxes that are used to select a date - "Valid from date" and "Valid To Date". When a date gets entered into the Valid from date textbox I want to automatically add 30 days and put this date into the valid to date textbox. So I added an onchange to the textbox:

<asp:TextBox runat="server" ID="txtValidFromDate" onchange="UpdateValidToDate(this.value)" Width="80px" rel="datepicker"></asp:TextBox>

function UpdateValidToDate(date){
        var ValidToDate = new Date(date);
        var numberOfDaysToAdd = 30;
        ValidToDate.setDate(ValidToDate.getDate() + numberOfDaysToAdd);
        document.getElementById('<%= txtValidToDate.ClientID %>').value = ValidToDate;
    }

The problem is the date format is 07/12/2016 so when I call ValidToDate.getDate() the format is wrong. The day and month are getting mixed up. So if I add this code I can see that the day gets set to 12 and the month gets set to 7 when it should be the other way around.

var day = ValidToDate.getDate();
var month = ValidToDate.getMonth()+1;

How do I format the date coming in from the textbox so when I add 30 days it returns the correct date?

user123456789
  • 1,914
  • 7
  • 44
  • 100

2 Answers2

0

I don't know a reliable way to parse dates with arbitrary formats using the pure JS Date API.

So either:

  1. Parse the date yourself and construct it from its components (e.g. use RegExp)
  2. Use a third party library like moment.js
Ovidiu Dolha
  • 5,335
  • 1
  • 21
  • 30
0

Try the below code with mm/dd/yyyy date format

var date = '12/07/2016';
var ValidToDate = new Date(date);
var numberOfDaysToAdd = 30;
ValidToDate.setDate(ValidToDate.getDate() + numberOfDaysToAdd);
document.write(ValidToDate.getDate()+'/'+(ValidToDate.getMonth()+1)+'/'+ValidToDate.getFullYear());

Update with dd/mm/yyyy date format

var date1 = '07/12/2016'; // let the format is dd/mm/yyyy
// convert date in mm/dd/yyyy format
d=date1.split('/');
date = d[1]+'/'+d[0]+'/'+d[2];
var ValidToDate = new Date(date);
var numberOfDaysToAdd = 30;
ValidToDate.setDate(ValidToDate.getDate() + numberOfDaysToAdd);
document.write(ValidToDate.getDate()+'/'+(ValidToDate.getMonth()+1)+'/'+ValidToDate.getFullYear());
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106