1

I am trying to get the difference between two dates (my birthday and the current date to get the time left until my birthday), But I want the output format in ('Year/Months/Days); How can I do that? that's what I've tried so far :

 const birthday = new Date ('11-20-2021').getTime();
 const today = new Date ().getTime();
 const dys = (1000*60*60*24);
 const months = (dys*30);
 let differance = birthday-today ; 
 const formatted = Math.round(differance/dys);
 console.log(formatted);`

thank you in advance

0stone0
  • 34,288
  • 4
  • 39
  • 64
  • what would you consider a month? Is the difference between `March 2nd` and `February 1st` 1 month and 1 day, or 29 days? – clod9353 Dec 13 '20 at 17:17
  • There are [many questions](https://stackoverflow.com/search?q=%5Bjavascript%5D+difference+between+dates+in+years%2C+month) on this already, with some good answers with and without libraries, like [this one](https://stackoverflow.com/a/35520995/257182), please excuse the shameless self promotion… :-) – RobG Dec 13 '20 at 23:15

4 Answers4

0

How do you feel about the modulo operator? :)

This is a common math operation, like finding change or such. Think of it this way, if you have a large number of days, say 397, you can get number of years by doing integer division (1), then you can get the number of days left by doing modulo by a year to get the remainder (in days) 397%365 = 32. Then you can repeat the process to get number of months remaining (1...assuming 30 day month) in that and again, modulo to get the final number of days 2 ...

I'm no javascript pro, but I think you need to use Math.floor(quotient) to get the result of division in integer format.

AirSquid
  • 10,214
  • 2
  • 7
  • 31
  • Honestly !! i was thinking exactly the same way you've looked at it, but I thought it may be some other ways to get around that, but thank you so much for taking time to answer my concern ;) appreciate you – Khaled Berhane Dec 13 '20 at 19:14
  • The [`%` multiplicative operator](https://tc39.es/ecma262/#sec-multiplicative-operators) in ECMAScript gives the remainder of dividing two numbers, it's not strictly a modulo operator, see [*JavaScript % (modulo) gives a negative result for negative numbers*](https://stackoverflow.com/a/4467624/257182). – RobG Dec 14 '20 at 00:10
0

this example compares between the current date and the date 2100/0/14 try the same concept in the example and i hope it helps:

var today, someday, text;
today = new Date();
someday = new Date();
someday.setFullYear(2100, 0, 14);

if (someday > today) {
  text = "Today is before January 14, 2100.";
} else {
  text = "Today is after January 14, 2100.";
}
document.getElementById("demo").innerHTML = text;
nabil497
  • 113
  • 1
  • 13
  • Sorry maybe i wasn't clear when writing my question but what I needed from that is to output exactly how many years, months, and days left until my birthday. For instance how many days left from today until March 3rd, 2021. – Khaled Berhane Dec 13 '20 at 19:17
0

Working with dates and differences can be difficult because there are a lot of edge cases. which is why I prefer to let a dedicated library handle this, like https://momentjs.com/

moment has a plugin (https://www.npmjs.com/package/moment-precise-range-plugin) which does exactly what you are looking for:

import moment from 'moment';
import 'moment-precise-range-plugin';

var m1 = moment('2014-01-01 12:00:00','YYYY-MM-DD HH:mm:ss');
var m2 = moment('2014-02-03 15:04:05','YYYY-MM-DD HH:mm:ss');
var diff = moment.preciseDiff(m1, m2, true); // {years : 0, months : 1, days : 2, hours : 3, minutes : 4, seconds : 5}
var str = `Years: ${diff.years}, Months: ${diff.months}, Days: ${diff.days} `; // 'Years: 0, Months: 1, Days: 2'
dpwr
  • 2,732
  • 1
  • 23
  • 38
  • I actually did but I am still having the ' moment.preciseDiff is not a function', I tried to find out where the problem is but it doesn't look like there is something obvious. I am putting the lines of code I wrote so maybe it'll give you an idea on what I am talking about `var m1 = moment('2017-05-17 00:00:00','YYYY-MM-DD HH:mm:ss'); var m2 = moment('2022-05-17 00:00:00','YYYY-MM-DD HH:mm:ss'); var diff = moment.preciseDiff(m1, m2); var str = `Years: ${diff.years}, Months: ${diff.months}, Days: ${diff.days} `; document.getElementById('Result').innerHTML = diff; ` – Khaled Berhane Dec 14 '20 at 12:51
  • Most likely you didn't import `moment-precise-range-plugin`. It's a plugin, so the import appears to be pointless, but it's not because it actually modifies the `moment` library. – dpwr Dec 14 '20 at 13:26
-1

If I got you right, I've done it this way. Haven't touched your original code, but added a function that calculates the dateTime output of the total days of difference.

const birthday = new Date('11-20-2021').getTime();
const today = new Date().getTime();
const dys = (1000 * 60 * 60 * 24);
const months = (dys * 30);
let totalDayserance = birthday - today;

const formatted = daysToDateTime(totalDayserance / dys);
console.log(formatted);


function daysToDateTime(totalDays) {
  var baseVal = '';
  var formedValues = [
    ['Years', 365],
    ['Months', 30],
    ['Days', 1]
  ];

  for (var i = 0; i < formedValues.length; i++) {
    var valueByGroup = Math.floor(totalDays / formedValues[i][1]); //by months

    if (valueByGroup >= 1) {
      baseVal += (valueByGroup + formedValues[i][0]) + ', ';
      totalDays -= valueByGroup * formedValues[i][1];
    }
  }

  return baseVal;
}
Selim Balci
  • 940
  • 2
  • 11
  • 26