Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first and last date of current month with JavaScript or jQuery [duplicate]

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'; 
like image 851
Moozy Avatar asked Nov 26 '12 19:11

Moozy


1 Answers

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 
like image 124
RobG Avatar answered Oct 26 '22 13:10

RobG