Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last day of the previous month in Javascript or JQuery

I have the following code to get the current day:

var month=new Array(12);
month[0]="January";
month[1]="February";
month[2]="March";
month[3]="April";
month[4]="May";
month[5]="June";
month[6]="July";
month[7]="August";
month[8]="September";
month[9]="October";
month[10]="November";
month[11]="December";

var d = new Date();
var curr_date;
if (d.getDate() == 1)
{
    curr_date = d.getDate();
}
else
{
    curr_date = d.getDate() - 1;
}

var curr_month = d.getMonth() + 1; //months are zero based
var curr_year = d.getFullYear();
var message_day = curr_year + "_" + curr_month + "_" + curr_date;
var sql_day = month[curr_month - 1].substring(0,3) + curr_date.toString() + curr_year.toString();

if (curr_date == "1")
    {
         document.write(sql_day + " " + message_day);
    }

This is great for getting the current day, but now i need to get the last day of the last month if it is the beginning of a new month.

right now this will produce:

Feb12012 2012_2_1

but what i need output is:

Jan312012 2012_1_31

Thanks

like image 847
some_bloody_fool Avatar asked Feb 01 '12 17:02

some_bloody_fool


People also ask

How do I get the last Sunday of the month in JavaScript?

A function to get the last Sunday of a month might be: /** * Returns last Sunday of month * * @param {Temporal. YearMonth} queryMonth - YearMonth to get last Sunday of * @returns {Temporal. Date} for last Sunday of queried month */ function getLastSunday(queryMonth) { let lastOfMonth = queryMonth.

How do you check if a date is in the past in JavaScript?

To check if date is in the past in JavaScript, we get the difference of the timestamp between the current date time and the given date. to call getTime to get the timestamp of each datetime in milliseconds. Then we get their difference and assign it to diff1 . If diff is bigger than 0, then givenDate is in the past.


1 Answers

var d=new Date(); // current date
d.setDate(1); // going to 1st of the month
d.setHours(-1); // going to last hour before this date even started.

now d contains the last date of the previous month. d.getMonth() and d.getDate() will reflect it.

This should work on any date api that wraps c time.h.

like image 182
Shiplu Mokaddim Avatar answered Oct 14 '22 10:10

Shiplu Mokaddim