Problem
As the title suggests, I’m having trouble figuring out how to use JavaScript or jQuery to get the start and last dates of the current month and format them as:
For November, for example, it should be:
var firstdate = '11/01/2012';
var lastdate = '11/30/2012';
Asked by Moozy
Solution #1
It’s very simple, and there’s no need for a library:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
or, if you 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);
Some browsers will consider two-digit years to be in the twentieth century, resulting in:
new Date(14, 0, 1);
1 January 1914 is given. To avoid this, create a Date and then use setFullYear to set its values:
var date = new Date();
date.setFullYear(14, 0, 1); // 1 January, 14
Answered by RobG
Solution #2
I used Datejs to fix it.
This is the first day’s warning:
var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);
The following is for the final day:
var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);
Answered by Moozy
Post is based on https://stackoverflow.com/questions/13571700/get-first-and-last-date-of-current-month-with-javascript-or-jquery