I'm making a countdown but right now it only gives a response if the date hasn't passed yet. But I want that if the date is passed already that it goes to the next year. How could I do that? I guess I need to use an "if" at my const with the date but I have no idea how to do that.
const difference = new Date(`01/01/${year}`) - new Date();
CodePudding user response:
Hello Simon, first of all, I want to tell you (as a tip) that you don't need to convert dates to calculate the difference between them. That being said, I recommend you use date-fns
for date calculations, with this library you will be able to use methods like endOfDay(date)
. If you still don't want to use any external library, you can use setHours method:
const now = new Date()
const endOfDay = new Date(new Date(now.toString()).setHours(23, 59, 59, 999))
const isBeforeEndOfDay = now <= endOfDay
console.log(isBeforeEndOfDay)
And to get the difference between the two dates you don't need to calculate if its the end of the day:
// To set two dates to two variables
const date1 = new Date("06/30/2019");
const date2 = new Date("07/30/2019");
// To calculate the time difference of two dates
const Difference_In_Time = date2.getTime() - date1.getTime();
// To calculate the no. of minutes between two dates
const Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
const Difference_In_Hours = Difference_In_Days * 24
console.log(Difference_In_Days, Difference_In_Hours)
// [...]