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/

2
  • 1
    This question is a bit unclear. Are you just trying to get yesterday? That's asked and answered here. 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. Commented May 3, 2017 at 21:39
  • This is really a duplicate of 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. Commented May 3, 2017 at 23:05

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

@RobG I actually hadn't done that before (wasn't sure exactly where on the toolbar it was). I've since updated it. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.