Reputation: 33
https://jsfiddle.net/yg4bk1wh/
I am trying to create a tool that reports the days remaining -
moment(1583884740000).diff(moment(), 'days')
but this is reporting incorrectly - almost as if the month index is not taken into consideration.
-- also if the days became negative - would want to obtain the value without the polarisation - so intead of "10 days remaining" -- it reads "finished 30 days ago"
-- https://www.calendar-12.com/days_between_dates
scenario 1 Start Date - February 12th End Date - March 10th
total days between the two dates - 27 days remaining days from now until end day - 33 days ^ campaign has yet to start
scenario 2 Start Date -January 6 End Date - March 10th
total days between the two dates - 64 days remaining days from now until end day - 33 days
so the campaign has been running (64-33) = 31 days [totaldays-remaining days] as such the campaign is (31/64 * 100) % complete [48%]
Upvotes: 0
Views: 171
Reputation: 1673
In your line with days remaining, you are using the current date instead of your first date. moment()
will return the current date and time.
m[2] = ["days remaining", moment(1583884740000).diff(moment(), 'days')];
Put your first timestamp in and the result will be 27 days remaining, which is correct.
m[2] = ["days remaining", moment(1583884740000).diff(moment(1581465600000), 'days')];
Here's a working fork of your fiddle: https://jsfiddle.net/bd91mjs7/2/
To solve your text problem you could calculate your remaining days beforehand and change the text accordingly:
let daysLeft = moment(1583884740000).diff(moment(1581465600000);
let daysLeftLabel = daysLeft < 0 ? 'finished ago' : 'days remaining'
var m = [];
m[0] = ["moment(date1)", moment(1581465600000).format('MMMM D YYYY')];
m[1] = ["moment(date2)", moment(1583884740000).format('MMMM D YYYY')];
m[2] = [daysLeftLabel, Math.abs(daysLeft), 'days')];
Note: Math.abs()
returns the absolute value, so that you don't get "-X days ago"
I'm not sure about the
"10 days remaining" -- it reads "finished 30 days ago"
part though, in my example it would read "days ago 10" instead of "days remaining -10". You may need to change the logic yourself there.
Update: as @nsevens stated, you are also using the wrong date format. Instead of d
, which gets you the day of the week, you should use D
which returns the day of the month (https://momentjs.com/docs/#/displaying/format/). I updated my example above.
Upvotes: 1
Reputation: 2835
In your jsfiddle, you're formatting the date wrong, which returns a wrong display date. See snippet:
console.log(moment(1583884740000).format('MMMM d YYYY'))
console.log(moment(1583884740000).format('MMMM D YYYY'))
<script src="https://unpkg.com/[email protected]/min/moment.min.js"></script>
moment(1583884740000).format('MMMM D YYYY')
returns 'March 11 2020' which is the correct amount of days after today.
Upvotes: 2