Update value of moment.js

1

I'm working with the date management library in Javascript Moment.js, and I'm trying to make a kind of calendar, in which, starting from the current date, pressing a button backs up on the date, and when clicking on other advances.

The main problem I have in that, if for example, today we are at 4/7/2017 and reduce the date, effectively, it goes backwards, but when you press later to increase, it increases, but from the date current, not from the date to which I have previously retreated (and vice versa).

I imagine that it will be necessary to update the Moment object with the respective dates to use them as a starting point, but I have not found a way to do it.

I add a simple example of code to make it more understandable (I would have created a snippet but I can not get it to recognize the javascript library).

Here we see two buttons:

<input type="button" value= "-" onclick='fecha(1,0)'/>
<input type="button" value = "+" onclick='fecha(0,1)'/>

Both buttons will call a function:

function fecha(restar, sumar){  
  var dia = moment();
  if(sumar == 1){
    dia = dia.add(sumar, "days");
    dia = dia.format("DD/MM/YYYY")
    console.log(dia);
  }
  if(restar == 1){
    dia = dia.subtract(restar, "days");
    dia = dia.format("DD/MM/YYYY");
    console.log(dia);
  } 
}

The problem is that when I want to add or subtract a date, always part of the current date, instead of from the date that has been reduced or increased.

I hope this clarifies a bit of clarity about my problem.

    
asked by AntonioMP87 04.09.2017 в 16:16
source

1 answer

1

The current day always comes out because you are assigning dia as moment() , which takes the current date.

You have to initialize the input as today's date and then do the calculations by taking the value of input .

To go from string to date (to add or subtract 1) you have to pass the value of input as parameter to the method moment and specifying the format you want

var  inputFecha = document.getElementById("fecha");

inputFecha.value = moment().format("DD/MM/YYYY");



function fecha(restar, sumar){  
 
  if(sumar == 1){
    inputFecha.value = moment(inputFecha.value, "DD-MM-YYYY").add(sumar, 'days').format("DD/MM/YYYY");

    console.log(inputFecha.value);
  }if(restar == 1) {
    inputFecha.value = moment(inputFecha.value, "DD-MM-YYYY").subtract(restar, 'days').format("DD/MM/YYYY");
    console.log(inputFecha.value);
  } 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>
<input type="button" value= "-" onclick='fecha(1, 0)'/>
<input type="text" id="fecha"/>
<input type="button" value = "+" onclick='fecha(0, 1)'/>

   
    
answered by 04.09.2017 / 17:19
source