I am trying to get moment.js to show me time until a specific date. I have that done doing this:
let date = 2017-03-27T12:00:00;
moment().to(date);
This shows: "in 10 days
".
I'd really like this to show "in 10 days and 2 hours
" or the two highest values. For example, 1 year and 5 months
, 4 minutes and 30 seconds
.
Is there a simple way to do this? I am currently working on a complicated method to handle this...
let years = moment(date).local().diff(moment(), 'years');
let months = (moment(date).local().diff(moment(), 'months'));
let days = (moment(date).local().diff(moment(), 'days'));
let hours = (moment(date).local().diff(moment(), 'hours'));
let minutes = (moment(date).local().diff(moment(), 'minutes'));
let seconds = (moment(date).local().diff(moment(), 'seconds'));
//The above values return total number each,
//For example, this could show 1 year, 14 months, 435 days, etc.
//The math below is supposed to make this say
//1 year, 2 months, 14 days, etc.
let yearsRemain = years;
let monthsRemain = months - (years *12);
let daysRemain = days - (Math.floor(months * 30));
let hoursRemain = hours - (days * 24);
let minutesRemain = minutes - (hours * 60);
let secondsRemain = seconds - (minutes * 60);
var dateArray = [
yearsRemain,
monthsRemain,
daysRemain,
hoursRemain,
minutesRemain,
secondsRemain
]
console.log(dateArray);
/*
returns [1, 1, 3, 23, 16, 46] for example
*/
the problem with this is when it comes to days. Since days in a year and days in a month vary, I was hoping moment.js would help me out. Is there a better way of doing this?
Eventually, I will be able to iterate through the array and find the two largest values to display how I'd like.