hodl
hodl

Reputation: 1420

javascript calculate number of days

I'm having hard time to get the right solution for this, so I need your help now.

date1 = "03/02/2012 09:51 pm"

date2 = "03/04/2012 06:00 pm"

Calculate the above example date into how many days diff. using JavaScript.

Upvotes: 1

Views: 473

Answers (3)

İrfan Erol
İrfan Erol

Reputation: 21

momentjs comes handy in such cases. You can run attached snippet to see results. It allows you to extract time difference easily. Also, you can work using several cultures and languages.

moment.locale('en');

var from = moment("2016-04-14 23:30");
var until = moment("2016-04-14 23:45");
var untilDay = moment("2016-04-15 03:45");
var untilMonth = moment("2016-03-14 06:33");

$('body').append(from.to(until) + "<br>");
$('body').append(from.to(untilDay) + "<br>");
$('body').append(from.to(untilMonth) + "<br>");
<!DOCTYPE html>
<html>

<head>
  <script src="https://cdn.jsdelivr.net/momentjs/2.10.6/moment-with-locales.min.js"></script>
  <script src="https://cdn.jsdelivr.net/momentjs/2.10.6/locales.min.js"></script>
  <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>

</body>

</html>

Upvotes: 0

Ohgodwhy
Ohgodwhy

Reputation: 50767

Remove the original post as to modify and inflect the proper answer

var date1 = new Date("2012-03-02");
var date2 = new Date("2012-04-15");
var daysDifference = new Date(date2 - date1);
var daysDifference = daysDifference/1000/60/60/24;
document.write(daysDifference);

Try it yourself.

Upvotes: -1

P. Galbraith
P. Galbraith

Reputation: 2527

var date1 = Date.parse("03/02/2012 09:51 pm");
var date2 = Date.parse("03/04/2012 06:00 pm");

var dayDiff = (date2 / (1000*60*60*24)) - (date1 / (1000*60*60*24));

Upvotes: 2

Related Questions