0

The dateToUnix() function below is meant to return a unix timestamp given a date as the parameter (in the form of "YYYY.MM.DD").

function dateToUnix(date) {
    return Math.floor(new Date(date).getTime() / 1000);
}

console.log(dateToUnix("2022.03.25")); // logs 1648180800 in Chrome

In Safari, the function returns NaN. How can I refactor my function so that it works in both browsers?

jgpixel
  • 103
  • 2
  • 6
  • `"2022.03.25"` isn't supported by the specification. Some browsers can support it and other browsers return `NaN`. – jabaa Mar 26 '22 at 02:21
  • Right, but how could I refactor that to make it be supported in Safari? @jabaa – jgpixel Mar 26 '22 at 02:27
  • Use ISO 8601 date format `"2022-03-25"` or pass separate numeric values to the `Date` constructor `new Date(2022,2,25)`. There are multiple solutions in the linked duplicate. – jabaa Mar 26 '22 at 02:29
  • Your first suggestion works, thank you! @jabaa – jgpixel Mar 26 '22 at 02:32

0 Answers0