Member-only story
An interesting line of JavaScript code
2 min readMay 8, 2023
This article will introduce you to some interesting code in JavaScript , which is very short, usually one line long, and can help us solve some problems very efficiently.
Time operation
Check if the date is valid
This method is used to check if the given date is valid:
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 17, 1995 03:24:00"); // true
Calculate the interval between two dates
This method is used to calculate the interval between two dates:
const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
dayDif(new Date("2021-11-3"), new Date("2022-2-1")) // 90
Find the date on the day of the year
The method used to detect the date given is on the day of the year:
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date()); // 307