0

I'm trying to get the day of the month before a Date, this is what I have

var date =  new Date();
var day = date.getDay();
var month = date.getMonth() + 1;
var year = date.getFullYear();

var yesterday = new Date(date.getTime());
yesterday.setDate(date.getDate() - 3);
var dayBefore = yesterday.getDay();
var MonthBefore = yesterday.getMonth() + 1;

On the log of yesterday I get

 Sun Apr 30 2017 16:24:33 GMT-0500

Not really yesterday, because I was trying to get a day before the current month, but I get the last month, now when I want to get the day and month of that date, so I use getDate() and getMonth(), I get the month correctly with

 MonthBefore = yesterday.getMonth() + 1;

this gives me 4 (april), but with the day (30) I get 0 using

dayBefore = yesterday.getDay();

Here is the jsfiddle: https://jsfiddle.net/4pf7bczv/

  • 1
    This question is a bit unclear. Are you just trying to get yesterday? That's [asked and answered here](http://stackoverflow.com/q/5511323/215552). But your question goes on to say something about the day before the current month, which is a bit unclear. Do you want the last day of the previous month? That's been asked and answered many times, [including here](http://stackoverflow.com/q/9100676/215552). – Heretic Monkey May 03 '17 at 21:39
  • This is really a duplicate of [*Add +1 to current date*](http://stackoverflow.com/questions/9989382/add-1-to-current-date), just change the sign. BTW, `yesterday.setDate(date.getDate() - 3)` will set the date to 3 days previous, not 1. – RobG May 03 '17 at 23:05

1 Answers1

3

getDay return the day of the week. getDate returns the day of the month.

try this:

var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();

var yesterday = new Date(date.getTime());
yesterday.setDate(date.getDate() - 3);
var dayBefore = yesterday.getDate();
var MonthBefore = yesterday.getMonth() + 1;


console.log(date)
console.log(yesterday)
console.log(month + '/' + day + '/' + year + " 11:59 pm")
console.log(MonthBefore + '/' + dayBefore + '/' + year + " 12:00 am")

console.log(yesterday.getDate());

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

NovaPenguin
  • 463
  • 3
  • 8
  • @RobG I actually hadn't done that before (wasn't sure exactly where on the toolbar it was). I've since updated it. Thanks! – NovaPenguin May 04 '17 at 14:01