Imagine you have a pet project, and its feature requires a few date-time calculation functions. However, it’s too small, and you don’t want to install additional dependencies. Or maybe your client doesn’t want to use libraries due to security concerns or performance optimization. Or simply, you don’t want to decide between moment.js, dayjs, or date-fns. Then this article is for you. Why not try plain JavaScript?
1. Get the First and Last Day of the Month:
You can get the first and last day of the month using Date
methods.
const getFirstDayOfMonth = (
date = new Date()
) => new Date(date.getFullYear(), date.getMonth(), 1);
const getLastDayOfMonth = (
date = new Date()
) => new Date(date.getFullYear(), date.getMonth() + 1, 0);
2. Calculate the Difference Between Two Dates:
You can calculate the difference between two dates using subtraction. This will give you the difference in milliseconds, which you can convert to other units as needed.
const date1 = new Date('2024-03-11');
const date2 = new Date('2024-01-01');
const differenceInMilliseconds = date1 - date2;
3. Formatting Dates:
You can format dates in various ways using Date
methods.
const date = new Date();
const formattedDate = `${date.getDate()}-${date.getMonth() + 1}-${date.getFullYear()}`;
4. Add/Subtract Days from a Date:
You can add or subtract days from a date by manipulating the milliseconds.
const date = new Date();
const numberOfDaysToAdd = 7;
date.setDate(date.getDate() + numberOfDaysToAdd);
5. Check if a Year is a Leap Year:
You can check if a year is a leap year by checking if it’s divisible by 4, unless it’s divisible by 100 but not 400.
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}
6. Get Current Unix Timestamp:
You can get the current Unix timestamp by using Date.now()
.
const timestamp = Date.now();
These are just a few examples of what you can do with dates in JavaScript without any external libraries. JavaScript’s built-in Date object provides a lot of functionality for handling dates and times.
[fluentform id="8"]