Explain Codes LogoExplain Codes Logo

Get first and last date of current month with JavaScript or jQuery

javascript
date-handling
javascript-date-object
timezone-issues
Alex KataevbyAlex Kataev·Oct 29, 2024
TLDR

Quickly find the first and last dates of the current month using the following JavaScript snippet:

const now = new Date(); // "Hello, Day 1! Nice to meet you!" - start of the month const firstDay = new Date(now.getFullYear(), now.getMonth(), 1); // "Bye, Bye, Days. See you next month!" - end of the current month const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0); console.log(firstDay, lastDay);

Deal with edge cases in date handling

JavaScript's Date object is a powerful tool, but careful handling is needed for edge cases:

  • Use setFullYear() when setting the year to avoid misinterpretation of two-digit years.
  • Timezones can alter date results. Use .toISOString() or .toLocaleDateString() for consistent date representation.
  • Keep in mind that JavaScript counts months from 0. January is 0 and December is 11 - yes, JavaScript starts counting from zero, just like arrays!

Dealing with other months

For the date boundaries of any given month, adapt the initial function like so:

function getMonthBoundaries(year, month) { // "Peeking inside a new month..." const firstDay = new Date(year, month, 1); // "...and we've reached the exit!" const lastDay = new Date(year, month + 1, 0); return { firstDay, lastDay }; }

Just call getMonthBoundaries(yourYear, yourMonth) to receive the boundaries of your choice.

Show off your dates in style

To display dates in the popular MM/DD/YYYY style:

function formatDate(date) { // "Hey there, I'm a single digit. Got any spare zeros?" - Single digit day let day = ('0' + date.getDate()).slice(-2); // "Could use some padding. It's cold out there!" - Single digit month let month = ('0' + (date.getMonth() + 1)).slice(-2); let year = date.getFullYear(); return month + '/' + day + '/' + year; }

This snippet adds zeros to single-digit days and months, keeping date formatting consistent.

Better dating with Datejs

Date manipulations are quick and easy with the Datejs library:

// "Date.today() - It's carpe diem time!" const now = Date.today(); // "Excuse me! Trying to get to the start here!" - First day of the month const firstDay = now.moveToFirstDayOfMonth(); // "Fast-forward to the last day, please!" - Last day of the month const lastDay = now.moveToLastDayOfMonth();

Format these dates using toString("MM/dd/yyyy") for added flair.

Are timezones interrupting your dates?

To get accurate dates irrespective of timezones, set the date to the start of the day in your local timezone:

const date = new Date(); // "Zero it out to blend in with the locals!" - Aligns the date to the start of the day date.setHours(0,0,0,0);