Date code does not work in JS

I bet it's something really stupid, but I'm tired and looking for a quick escape, so please pamper me. The goal is to be able to add arbitrary days to a date built from a type string 2015-01-01.

 firstDate = '2015-01-01';
 var t1_date = new Date(firstDate);

 t1_date.setTime( t1_date.getTime() + 90 * 86400000 );
 lastDate = getFormattedDate(t1_date);
 console.log("Two dates: ", firstDate, lastDate);

function getFormattedDate(date) {
  var year = date.getFullYear();
  var month = date.getMonth().toString();
  month = month.length > 1 ? month : '0' + month;
  var day = date.getDate().toString();
  day = day.length > 1 ? day : '0' + day;
  return year + '-' + month + '-' + day;
}

And then:

I get a conclusion that is wrong because I add 90 days.

Two dates:  2015-01-01 2015-02-31
+3
source share
3 answers

The problem is this line:

var month = date.getMonth().toString();

The Date.getMonth () function returns "month (0-11) on the specified date according to local time." January 0, December 11, so you need to add 1 to the output:

var month = "" + (date.getMonth()+1);
+3
source

var month = date.getMonth().toString(); , 0, 1, . date.getMonth(); 0 .. 11.

firstDate = '2015-01-01';
var t1_date = new Date(firstDate);
console.log("before conversion");
console.log(t1_date);//before conversion
t1_date.setTime( t1_date.getTime() + 90 * 86400000 );
console.log("after conversion");
console.log(t1_date);//after conversion
lastDate = getFormattedDate(t1_date);
console.log("Two dates: ", firstDate, lastDate);

function getFormattedDate(date) 
{
  var year = date.getFullYear();
  var month = date.getMonth();
  var month1=(month+1).toString();
  month1 = month1.length > 1 ? month1 : '0' + month1;
  var day = date.getDate().toString();
  day = day.length > 1 ? day : '0' + day;
  return year + '-' + month1 + '-' + day;
}
0

Date, . ISO *, , , ES5 UTC, ECMAScript 2015 ( ), UTC , ( NaN).

, .

ISO .

* .

function parseISODate(s) { 
  var b = s.split(/\D/);
  var d = new Date(b[0], --b[1], b[2]);
  return d && d.getMonth() == b[1]? d : new Date(NaN);
}

document.write(parseISODate('2015-01-01') + '<br>');

function toISODate(date) {
  function z(n){return ('0'+n).slice(-2)}
  return date.getFullYear() + '-' + z(date.getMonth() + 1) + '-' +  z(date.getDate());
}

document.write(toISODate(parseISODate('2015-01-01')));
Hide result

90 , 90 :

var d = new Date(2015,0,1);   // 1 January 2015
d.setDate(d.getDate() + 90);  // add 90 days
document.write(d.toLocaleString());  // 1 April 2015
Hide result
0

Source: https://habr.com/ru/post/1626283/


All Articles