Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first and last date of the previous month in JQuery

I have this script,

 var today = new Date();
 var dd = today.getDate();
 var ddd = today.getDate()-1;
 var dddd = today.getDate()-2;

 var mm = today.getMonth()+1; //January is 0!
 var yyyy = today.getFullYear();
 if(dd<10){
   dd='0'+dd
 } 
 if(mm<10){
   mm='0'+mm
 } 
 if(ddd<10){
   ddd='0'+ddd
 } 

 var today = dd+'/'+mm+'/'+yyyy;
 var d2 = ddd+'/'+mm+'/'+yyyy;
 var d3 = dddd+'/'+mm+'/'+yyyy;

With this i obtain the last 3 days of the current day but in this case today is 02 if i rest two days i obtain 0 but i want in this case the last day of the previous month, how can do this?

Here is my fiddle

like image 967
victor Avatar asked Feb 03 '16 05:02

victor


People also ask

How do you find the first day of the previous month?

=EOMONTH(date,-2)+1 The EOMONTH function operates by calculating the amount of days and months that it must roll back before determining the first day of the previous month.

How to get last day of previous month in js?

Use the Date() constructor to get the first and last day of the previous month. The first 3 parameters the Date() constructor takes are the year, month and day of the month. The constructor returns a new Date object according to the supplied parameters.

How to get first and last Date of previous month in Java?

Create a calendar object. Calendar cal = Calendar. getInstance(); Use the getActualMaximum() method to get the last day of the month.


2 Answers

That's the first day of the current month new Date(now.getFullYear(), now.getMonth(), 1) to get the last day of the previous month create a date 1-day earlier: new Date(now.getFullYear(), now.getMonth(), 1 - 1).

To get the first day of the previous month we should substract 1 from the month component new Date(now.getFullYear(), now.getMonth() - 1, 1) but there is an issue if the current month is January (0) and the previous month is December (11). Hence I wrapped the month expression creating a cycle so it always returns a positiove value.

var now = new Date();
var prevMonthLastDate = new Date(now.getFullYear(), now.getMonth(), 0);
var prevMonthFirstDate = new Date(now.getFullYear() - (now.getMonth() > 0 ? 0 : 1), (now.getMonth() - 1 + 12) % 12, 1);

var formatDateComponent = function(dateComponent) {
  return (dateComponent < 10 ? '0' : '') + dateComponent;
};

var formatDate = function(date) {
  return formatDateComponent(date.getMonth() + 1) + '/' + formatDateComponent(date.getDate()) + '/' + date.getFullYear();
};

document.write(formatDate(prevMonthFirstDate) + ' - ' + formatDate(prevMonthLastDate));
like image 92
Alexander Elgin Avatar answered Oct 23 '22 13:10

Alexander Elgin


Try using bellow

var date = new Date();
var monthStartDay = new Date(date.getFullYear(), date.getMonth(), 1);
var monthEndDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
like image 36
Sujithrao Avatar answered Oct 23 '22 12:10

Sujithrao