0

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();
  • How to compare two dates: https://stackoverflow.com/a/493018/8583450 – Spirit Pony Jun 14 '22 at 08:22
  • Your question and your code don't seem to be attempting the same thing, removing all of the surrounding "countdown" parts, what exactly are you stuck on? Finding the difference between today and the start of this year? or the closest year? or something else? – DBS Jun 14 '22 at 08:23

1 Answers1

0

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)

// [...]
Toni Bardina Comas
  • 1,670
  • 1
  • 5
  • 15
  • Thank you for your answer. But i wanna show how many days, hours, minutes and seconds are between. So not only the hours, minutes and seconds. Thats also possible? I'm sorry but i'm just beginner with Javascript. –  Jun 14 '22 at 08:44
  • I just edited the post with a way of calculating it - [Simon](https://stackoverflow.com/users/17489239/simon-wyns) – Toni Bardina Comas Jun 14 '22 at 09:07