HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Get the first or last date of a month using JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
lastjavascriptdatemonthfirstgettheusing

Problem

Getting the first date of a month is usually pretty simple. But how about getting the last date of a month? Here's how you can do both using JavaScript.
Given any Date object, you can use Date.prototype.getFullYear() and Date.prototype.getMonth() to get the current year and month from the given date. In order to get the first date of a month, you just need to create a new Date object, using these methods, and set the day to 1.
In order to get the last date of a month, we can use a clever trick on top of the previous code snippet. Instead of setting the day to 1, we can set it to 0. This will give us the last day of the previous month. In order for this to work, we'll need to advance the month by 1 as well.

Solution

const firstDateOfMonth = (date = new Date()) =>
  new Date(date.getFullYear(), date.getMonth(), 1);

firstDateOfMonth(new Date('2015-08-11')); // '2015-08-01'


In order to get the last date of a month, we can use a clever trick on top of the previous code snippet. Instead of setting the day to 1, we can set it to 0. This will give us the last day of the previous month. In order for this to work, we'll need to advance the month by 1 as well.

Code Snippets

const firstDateOfMonth = (date = new Date()) =>
  new Date(date.getFullYear(), date.getMonth(), 1);

firstDateOfMonth(new Date('2015-08-11')); // '2015-08-01'
const lastDateOfMonth = (date = new Date()) =>
  new Date(date.getFullYear(), date.getMonth() + 1, 0);

lastDateOfMonth(new Date('2015-08-11')); // '2015-08-31'

Context

From 30-seconds-of-code: first-last-date-of-month

Revisions (0)

No revisions yet.