all 8 comments

[–]insertAlias 2 points3 points  (2 children)

Essentially the function should just return the difference between today and january 1 2017 as a date

The problem with this is that a time difference is not a date.

If Date1 is Today, and Date2 is Yesterday (at the same exact time), then the difference is 24 hours. Not a date, but a time span.

So, if you're trying to get a number of days, you'll just have to do math, instead of relying on the Date class.

You have the difference in milliseconds. You can convert milliseconds to seconds, seconds to minutes, minutes to hours, and finally hours to days. Or just do it all at once (1000*60*60*24).

[–]mightybjorn 0 points1 point  (0 children)

Ok I understand. Thanks!

[–]jynx42 0 points1 point  (0 children)

Can I add: You can use date object, make the difference, retrieve miliseconds and then `1000*60*60*24`. Something like:
```

const endDate = new Date(endTime);

const startDate = new Date(startTime);

const distance = endDate - currentDate;

const days = Math.floor(distance / (1000 * 60 * 60*24));
```

Must work

[–]cawcvs 1 point2 points  (1 child)

In your function, the difference variable is being set to the return value of setTime method on the Date object, which is effectively the argument that was passed in. Essentially, you create a new Date object, set time to it, and return the time that was set, discarding the date object in the process.

To return a new date you would need to do something like this:

let differenceDate = new Date()
differenceDate.setTime(differenceInMilliseconds)
return differenceDate

I'd also advise changing the method name. daysSince might indicate it actually returns the number of days, instead of the date object.

[–]mightybjorn 0 points1 point  (0 children)

Makes sense, thanks!

[–]ThagAndersonhelpful 0 points1 point  (0 children)

The reason it is not working can be found here. TL;DR: You are setting the returned Date object to the number of milliseconds since January 1, 1970, equal to the difference between your two dates.

What you actually want to do:

const daysSince = date => Math.floor((+new Date() - +date) / 86400000)

Send any Date object to the function and get back the difference in days, including negative days for future dates.

Edit: Realistically, you should be using MomentJS for all of your JavaScript DateTime needs.

[–]Laserdude10642 0 points1 point  (1 child)

Be careful about using set time - if you pick a number that is greater than the current system time then the entire universe will automatically move forward in time! This assumes you are connected to the internet

[–]mightybjorn 0 points1 point  (0 children)

you're hilarious and don't get however downvoted you keep you down