0

I am currently trying to figure out how to calculate the difference in days between a date pulled through from an API and today's date.

this is the code I have used to get todays date in the format that matches date from the API:

var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = dd + '/' + mm + '/' + yyyy;

This twig code pulls the date of the API through

{{ job.date }}

What I need to work out to do and struggling with is

today - {{ job.date }} = Difference in Days

I have looked through the articles here but I have struggled to find one that I can understand.

Could this be done with twig?

Any help would be appreciated and even more so if someone could put the snippet together for me.

DarkBee
  • 16,592
  • 6
  • 46
  • 58
Alex Posterns
  • 23
  • 1
  • 8
  • If you create `Date` objects from both, you can subtract them to get the difference in milliseconds. Now divide by `24 * 3600 * 1000` to get days. –  Oct 06 '19 at 14:53
  • @ChrisG: You should probably also round the answer to deal with the subtleties of Summer Time/Daylight Saving Time. – Scott Sauyet Oct 06 '19 at 16:14

3 Answers3

1

jQuery approach with help of this post

//split
var todayArr = ('11/03/2019').split('/');
var startDateArr = ('10/03/2019').split('/');

//change format
var today = `${todayArr[2]}-${todayArr[1]}-${todayArr[0]}`
var startDate = `${startDateArr[2]}-${startDateArr[1]}-${startDateArr[0]}`

//calculate
var diff = new Date(Date.parse(today) - Date.parse(startDate));
var days = diff/1000/60/60/24;

console.log(days);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Masoud Keshavarz
  • 2,166
  • 9
  • 36
  • 48
0

You can do something like this......

function countDays(firstDate, secondDate) {

    var startDay = new Date(firstDate);
    var endDay = new Date(secondDate);
    var millisecondsPerDay = 1000 * 60 * 60 * 24;

    var millisBetween = startDay.getTime() - endDay.getTime();
    var days = millisBetween / millisecondsPerDay;

    // Round down.
    alert(Math.floor(days));

}
Salim Djerbouh
  • 10,719
  • 6
  • 29
  • 61
Chand Jogani
  • 146
  • 12
  • You might add a `round` to this to get consistent answers in the face of Summer Time/Daylight Saving Time. Also note that `millisBetween = startDay - endDay` will give you the same result as calling `getTime()` on each. – Scott Sauyet Oct 06 '19 at 16:19
0

If your date from api is "06/10/18" in "dd/mm/yy" format then

let date = "06/10/18";
let values = date.split("/");
date = new Date("20"+values[2],values[1]-1,values[0]);//months are from  0 to 11
let currDate = new Date();
let diff = currDate.getTime() - date.getTime();
diff = diff/1000; // seconds
diff = diff/60; // minutes
diff = diff/60; // hours
diff = diff/24; //days

let days = Math.round(diff);
Akshay Bande
  • 2,491
  • 2
  • 12
  • 29