412

As title says, I'm stuck on finding a way to get the first and last date of the current month with JavaScript or jQuery, and format it as:

For example, for November it should be :

var firstdate = '11/01/2012';
var lastdate = '11/30/2012';
1

2 Answers 2

1109

Very simple, no library required:

var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

or you might prefer:

var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);

EDIT

Some browsers will treat two digit years as being in the 20th century, so that:

new Date(14, 0, 1);

gives 1 January, 1914. To avoid that, create a Date then set its values using setFullYear:

var date = new Date();
date.setFullYear(14, 0, 1); // 1 January, 14
22
  • 2
    tried with code in accepted answer, I get firstDay as "Fri Aug 01 2014 00:00:00 GMT+0800 (SGT)" and lastDay as "Sun Aug 31 2014 00:00:00 GMT+0800 (SGT)" for the current month which is not correct answer. Has something changed ?
    – Kush
    Aug 26, 2014 at 8:32
  • 1
    @Kush what answer are you expecting exactly? Aug 26, 2014 at 10:12
  • 5
    as asked in question by @moozy, i am looking for same: var firstdate = '11/01/2012'; var lastdate = '11/30/2012';
    – Kush
    Aug 26, 2014 at 10:40
  • 9
    For those like me who wondered about the use of "December+1" and day "0" of the month to get the last day of the previous month, it all works per the spec; see developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    – Ed Staub
    Oct 24, 2015 at 3:31
  • 2
    love the simplicity!
    – Kitson
    Feb 17, 2020 at 22:00
24

I fixed it with Datejs

This is alerting the first day:

var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);

This is for the last day:

var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.