0

I'm receiving from the BE a date value, I need to get the remaining seconds. I am successful, but only if the date is in the current month, if the given date is the next month I'm not sure how to proceed without any library? `

For now I have this working code: `

 const convertToSeconds(date: string) {
      const startDateTime = new Date();
      const endDateTime = new Date(date);

      const secondsUntilExpiration = Math.abs(
        (startDateTime.getTime() - endDateTime.getTime()) / 1000
      );

      if (startDateTime > endDateTime) {
        return -secondsUntilExpiration;
      }

      return secondsUntilExpiration;
  }
  • 1
    why would it be different in a different month? Also you don't need the condition `startDateTime > endDateTime` just remove the `Math.abs` and subtract in the other order: `const secondsUntilExpiration = (endDateTime.getTime() - startDateTime.getTime()) / 1000;` – pilchard Oct 30 '22 at 22:18
  • As @pilchard suggested, there's no reason for this code to work only if the given date is in the current month. Please, provide a couple examples of the string input you are passing to the function to understand it better. It would be great if you edit your question by providing a working and a no-working example – radar155 Oct 30 '22 at 22:58
  • The body can be simply `return (Date.parse(date) - Date.now()) / 1000`. Also see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Oct 31 '22 at 03:52

0 Answers0