11

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

M.A.K. Ripon
  • 2,070
  • 3
  • 29
  • 47
victor
  • 507
  • 1
  • 7
  • 20
  • If you create three date objects, then subtract the number of milliseconds in a day (1000 * 60 * 60 * 24), you have a date that is yesterday, regardless of months, years, whatever. Now repeat three times – adeneo Feb 03 '16 at 05:27
  • Already solved at this link http://stackoverflow.com/questions/10931288/how-to-add-subtract-dates-with-javascript – mmuzahid Feb 03 '16 at 05:42
  • @adeneo that's not true for boundaries on daylight savings which are 23 or 25 hours – Patrick Roberts Feb 03 '16 at 05:52
  • I provided you a working snippet with 4 lines of code that produces a result exactly the same as you desire. What else do you need? – Alexander Elgin Feb 03 '16 at 06:47

9 Answers9

27

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));
Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50
  • Im sorry to answer to late, thanks for your suppor only have question, which number i need to change to obtain the previous month? i ask this be cause i always try your code's to understand – victor Feb 03 '16 at 07:06
  • @victor It is for the previous month. Have you run the code in the snippet? – Alexander Elgin Feb 03 '16 at 07:15
  • Im sorry, was my mistake, i change the date to march 2 to check the previous date, with your code how can convert numbers down of 10 like 01 02 03 04 05... in my code i have `if dd < 10 { dd = '0' + dd }` to change it – victor Feb 03 '16 at 07:22
  • @victor I don't understand what you are asking. Is it a new problem / question? – Alexander Elgin Feb 03 '16 at 07:30
  • no, is not an another question, is only about your result, if you check the date is like m/d/yyyy (1/1/2016) and i want to change the format of your date like mm/dd/yyyy (01/01/2016) – victor Feb 03 '16 at 07:36
  • @victor I guess I've understood you. You mean the date formatting with leading '0', right? Check the updated answer – Alexander Elgin Feb 03 '16 at 07:37
  • 2
    @AlexanderElgin unfortunately that doesn't work if the current month is January. If `now = 2016/01/05` then `prevMonthFirstDate = 2016/12/01` which is wrong. – AndyS Nov 15 '16 at 07:21
  • @AndyS Thanks for the report. I've fixed it. – Alexander Elgin Aug 15 '17 at 14:01
4

You can do it like this

//one day previous  Date
var date = new Date();
date.setDate(date.getDate() - 1);
console.log(date.getDay());

//for previous month last date 
var date = new Date();
date.setDate(0);
console.log(date);

//for perivous Month First date
var date = new Date();
date.setDate(0);
date.setDate(1);
console.log(date);
M.A.K. Ripon
  • 2,070
  • 3
  • 29
  • 47
Roli Agrawal
  • 2,356
  • 3
  • 23
  • 28
  • The topic starter asked the PREVIOUS month first and last dates (not the previous day). – Alexander Elgin Feb 03 '16 at 05:49
  • @AlexanderElgin Thanks for suggestion i have edited it – Roli Agrawal Feb 03 '16 at 06:06
  • Thanks for your answer, but if i wrong, with your previous month last date i obtain only the firts month of the year, i change the current date to march 2 and i get january 31 and the correct date is feb 29 – victor Feb 03 '16 at 06:13
  • But when i am doing like this var date=new Date("March 2, 2016 01:00:00"); date.setDate(0); console.log(date); I am getting 29 feb only – Roli Agrawal Feb 03 '16 at 06:22
3

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);
Sujithrao
  • 789
  • 3
  • 12
  • 27
1

Try this: get today's date and set date to 1 which will get first of the current month. Then set hour to -1 which will shift it to previous months last day. Then set day to 1 to get first day of previous month.

var today = new Date();
var dd = today.getDate();

today.setDate(1); // going to 1st of the month
today.setHours(-1); // going to last hour before this date even started.
var lastDay = today.toLocaleDateString('en-GB', {  
                              year: 'numeric',
                              month: 'numeric',
                              day: 'numeric'
                          }).split(' ').join('-');

alert("last day of previous month " + lastDay);

today.setDate(1); // going to 1st of the previous month

var firstDay = today.toLocaleDateString('en-GB', {  
                              year: 'numeric',
                              month: 'numeric',
                              day: 'numeric'
                          }).split(' ').join('-');

alert("first day of previous month " + firstDay);

JSFiddle Demo

Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
  • With your code how can obtain the date in this way dd/mm/yyyy, be cause with this i obtain a full date – victor Feb 03 '16 at 05:41
  • please check my edited answer where I have formatted the date to desired format of dd/mm/yyyy. You can modify `toLocaleDateString` method as per your requirement. – Bhushan Kawadkar Feb 03 '16 at 05:51
1

What I have guessed is if current month is February then your output should be 1,31 because January's first day and last day is 1 and 31. So if that is the case then

var toDay = new Date();
var myDate = new Date(2016,toDay.getMonth()-1);
Fri Jan 01 2016 00:00:00 GMT+0530 (India Standard Time)

This will be assigned with the first day of the previous month.

Also, for the second case

var myDate = new Date(2016, toDay.getMonth());
myDate = new Date(myDate -1);
Sat Jan 31 2015 23:59:59 GMT+0530 (India Standard Time)

You can just use myDate to find whatever you want.

Pallav Jha
  • 3,409
  • 3
  • 29
  • 52
0

A convenient trick to get the end of last month is the take current date and use setDate(0). Then use that that to create a new date object and setDate(1) for beginning of the month

var prevMonthEnd = new Date();
prevMonthEnd.setDate(0);
var beginLastMonth = new Date(prevMonthEnd);
beginLastMonth.setDate(1);


console.log([beginLastMonth.toString(), prevMonthEnd.toString()])
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

    var firstDay = new Date();
    var secondDay = new Date();
    var thirdDay = new Date();


  //Now say you want to set secondDay as before 2 days

    secondDay.setDate(secondDay.getDate()-2);

//Now say you want to set thirdDay as after 2 days  

        thirdDay.setDate(thirdDay.getDate()+2);
        alert("firstDay: "+firstDay+", secondDay:"+secondDay+", thirdDay:"+thirdDay);
        alert("date of thirdDay: dd/mm/yyyy  "+thirdDay.getDate()+"/"+ (thirdDay.getMonth()+1) +"/"+thirdDay.getFullYear()); 
zakaiter
  • 439
  • 3
  • 11
  • Hope this is what you are looking for. Cheers!! – zakaiter Feb 03 '16 at 06:45
  • i create a confuse with answer to @Mytri, be cause he put a solution to my question but if you check he set a january and always obtain the same date like jan 31, but i want the last three days of the current date – victor Feb 03 '16 at 06:54
  • var today= new Date(); var firstDay = new Date(); var secondDay = new Date(); var thirdDay = new Date(); firstDay.setDate(firstDay.getDate()-1); secondDay.setDate(secondDate.getDate()-2); thirdDay.setDate(thirdDay.getDate()-3); This is the way of setting previous days or next days date – zakaiter Feb 03 '16 at 07:13
0

I know many people have already answered it but I just figure out a 3 line solution so I thought I could share it in case anyone needs it.

let date = new Date();
let firstDay = new Date(date.getFullYear(), date.getMonth() - 1, 2);
let lastDay = new Date(date.getFullYear(), date.getMonth(), 1);
console.log(firstDay.toISOString(), lastDay.toISOString())

This solution works dynamically even if the current month is January, this method will auto-detect the previous year.

Example:

If the current date is: 2022-01-12

Previous month's first day: 2021-12-01

Previous month's last day: 2021-12-31

**Additionally you can set the time of both dates to 00:00:00 by using setUTCHours like this:

let date = new Date();
let firstDay = new Date(date.getFullYear(), date.getMonth() - 1, 2);
firstDay.setUTCHours(0,0,0,0);
let lastDay = new Date(date.getFullYear(), date.getMonth(), 1);
lastDay.setUTCHours(0,0,0,0);
console.log(firstDay.toISOString(), lastDay.toISOString())

Here's a working Fiddle example in case you need it.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Ahmad Habib
  • 2,053
  • 1
  • 13
  • 28
0
var mydate = new Date(2020,2,1); // march 1st 2020 leap year
var lastdate = new Date(mydate.getFullYear(),mydate.getMonth(),0);// get last date of prev month
var firstdate = new Date(lastdate.getFullYear(), lastdate.getMonth(), 1);//get first date using last date

alert('' + firstdate.toDateString() + '');
alert('' + lastdate.toDateString() + '');
srinidhi
  • 61
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 29 '22 at 07:17