Get first and last date of current month with JavaScript or jQuery
Quickly find the first and last dates of the current month using the following JavaScript snippet:
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 is0
and December is11
- 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:
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:
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:
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:
Was this article helpful?