Decrease javascript dates

Asked

Viewed 212 times

-1

I’m trying to use Moment.js but it’s bone, see?!!!

I have 2 fields that return the PHP date in the dd/mm/yyyy format. I want to show in a third field the difference between these dates. For example: 09/25/2018 and 09/30/2018 the answer has to be 5 days. Obviously in PHP I already did, however if the user changes a field of these update in the third.

In the same example above, if you go from 25/09/2018 to 26/09/2018 auto update in the third field.

I made a bagasse fiddle: http://jsfiddle.net/becw281u/

  • A good start would be to take a closer look at the documentation, the date you are passing to the function Moment() is not correct. https://momentjs.com/docs/#/Parsing/

  • I appreciate the comment, but I looked at the documentation and I didn’t understand much. As I said, I already have the date in that format and I realized that I needed to change its format so that Moment.js understood, but I don’t know how to do it...

  • It is always good to mark an answer as accepted when it solved your problem. See how in https://i.stack.Imgur.com/jx7Ts.png and why in https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

  • I still have a low reputation, I can’t score. It’s not bad will, so I posted the thanks.

2 answers

4


From what I understand, you want to calculate the difference in days between two dates, right?

Below is the change in the code quoted in the question:

var dtconclusao = document.getElementById("dtconclusao").value;
var dtfim = document.getElementById("dtfim").value;
var data1 = moment(dtconclusao, 'DD/MM/YYYY');
var data2 = moment(dtfim, 'DD/MM/YYYY');
var diferenca = data2.diff(data1, 'days');

alert(diferenca);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<input type="hidden" id="dtconclusao" value="25/09/2018" />
<input type="hidden" id="dtfim" value="30/09/2018" />

  • Perfect! Thank you my dear!

1

Moment.min.js => 51Kb

momentDoLeo.js => 1Kb

Use the momentDoLeo.js see how it works

    //momentDoLeo.js

    var dtconclusao = document.getElementById("dtconclusao").value;
    dtconclusao = dtconclusao.split("/").reverse().join("-");

    var dtfim = document.getElementById("dtfim").value;
    dtfim = dtfim.split("/").reverse().join("-");

    var datafinal = new Date(dtfim);
    var datainicial = new Date(dtconclusao);

    var difDias = (parseInt((datafinal - datainicial) / (24 * 3600 * 1000)));
    
     document.getElementById("numeroDias").value=difDias;
<input type="hidden" id="dtconclusao" value="25/09/2018" />
<input type="hidden" id="dtfim" value="30/09/2018" />

<input type="text" id="numeroDias" name="numeroDias"/>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.