0

I have a textfield that inputs date in this format: yyyy-mm-dd, how can I add a day to that users input? I have the following code but it doesnt work...

users_date = document.getElementById('users_date').value;    
var date = new Date(users_date);
var next_date = new Date();
next_date .setDate(date.getDate()+1);
document.getElementById('next_date').value = next_date;

The first problem is the format of the date in the second is like 'Mon Aug 05 2013 16:24:40 GMT-0500 (Hora est. Pacífico, Sudamérica)'

The second problem is that when the user input the fist day of the month like '2013-01-01' or '2013-08-01' it displays 'Sun Sep 01 2013 16:26:06 GMT-0500 (Hora est. Pacífico, Sudamérica)' ALWAYS

For example if user inputs 2013-01-01 I want another textfield to be 2013-01-02 or 2013-08-31 it displays 2013-09-01, how can I do that?

Thanks!!

ITS NOT DUPLICATE BECAUSE THE OTHER POST DOESN'T FORMAT THE DATE!!!!

joseagaleanoc
  • 575
  • 2
  • 7
  • 20

2 Answers2

1

Prior to ES5 there was no standard for parsing dates. Now there is a format that is a version of ISO8601, however it isn't supported by all browsers in use and is not typically used for user input.

Normally a format is requested or a "date picker" used that returns a specific format. From there, it's quite simple to parse the string to create a Date object:

// s is date string in d/m/y format
function stringToDate(s) {
  var b = s.split(/\D/);
  return new Date(b[2], --b[1], b[0]);
}

For ISO8601 format (y-m-d), just change the order of the parts:

// s is date string in y/m/d format
function isoStringToDate(s) {
  var b = s.split(/\D/);
  return new Date(b[0], --b[1], b[2]);
}

To add one day to a Date object, just add one day:

var now = new Date();
var tomorrow = now.setDate(now.getDate() + 1);
RobG
  • 142,382
  • 31
  • 172
  • 209
0

This should work:

var date = new Date(document.getElementById('users_date').value);
var next_date = new Date(date.getTime() + 24*60*60*1000); // adding a day

document.getElementById('next_date').value = next_date.getFullYear() + "-" +
                            (next_date.getMonth()++) + "-" + next_date.getDate();

Please, note that Date#getMonth() is zero-based. Hence, the increment.

Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89