The next day does not work using setDate

Try clicking the next and prev button to set the date using JS.

This does not work when I plus one day and try to get the date tomorrow.

$('#next_date').click(function(e) {
  var get_selected_date = "2015-12-14",
  nextDay = get_selected_date.split('-')[2] + 1,
  selectedDate = new Date(get_selected_date),
  date = new Date(selectedDate.setDate(nextDay));
  console.log(date);
});

But I manage to get the previous date using the same logic, only minus one day, as shown below

$('#prev_date').click(function(e) {
  var get_selected_date = "2015-12-14",
  nextDay = get_selected_date.split('-')[2] + 1,
  selectedDate = new Date(get_selected_date),
  date = new Date(selectedDate.setDate(nextDay));
  console.log(date);
});
+4
source share
2 answers

, , , , - 1 14, . , . JavaScript . , .

- ( , ):

string + string = string
string + number = string
number + string = string
string - number = number
number - string = number
string - string = number
+string + number = number (read below)

, get_selected_date.split('-')[2], int, parseInt(str), , "". . :

nextDay = +get_selected_date.split('-')[2] + 1

selectedDate.setDate(nextDay);

selectedDate

date = new Date(selectedDate.setDate(nextDay));

setDate() , , , .

: var . .

+1
    var str = '2015-12-14';
    str = str.split(/\D+/);
    str = new Date(str[0], str[1] - 1, (parseInt(str[2]) + 1)); 

str '2015-12-15'

//str [2] - , str [2]) + 1

, str = (str [0], str [1] - 1, (parseInt (str [2]) - 1));

str '2015-12-13'

0

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


All Articles