Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript Finds Last Month (or Next Month)


May 09, 2021 CoffeeScript


Table of contents


Find the last month (or the next month)

Problem

You need to calculate relevant date ranges such as "last month" and "next month".

Solution

By adding or subtracting the numbers for the month, JavaScript's date constructor fixes the math.

# these examples were written in GMT-6
# Note that these examples WILL work in January!
now = new Date
# => "Sun, 08 May 2011 05:50:52 GMT"

lastMonthStart = new Date 1900+now.getYear(), now.getMonth()-1, 1
# => "Fri, 01 Apr 2011 06:00:00 GMT"

lastMonthEnd = new Date 1900+now.getYear(), now.getMonth(), 0
# => "Sat, 30 Apr 2011 06:00:00 GMT"

Discuss

JavaScript's date objects handle the months and days that overflow and overflow, and adjust the date objects accordingly. F or example, you can ask to find the 42nd day of March and you will get April 11.

The JavaScript object stores the number of years for each year starting at 1900, the month is an integer from 0 to 11, and the date is an integer from 1 to 31. I n the above solution, the start date of the last month is the first day of the month required in the current year, but the month is from -1 to 10. If the month is -1, the date object will actually return to December of the previous year:

lastNewYearsEve = new Date 1900+now.getYear(), -1, 31
# => "Fri, 31 Dec 2010 07:00:00 GMT"

The same is said for overflows:

thirtyNinthOfFourteember = new Date 1900+now.getYear(), 13, 39
# => "Sat, 10 Mar 2012 07:00:00 GMT"