0

Can you help me with this problem? I tried to make a function that receives a parameter of type Date e.g. 12.11.2020. I want it to return the previous day.

function getPreviousDay(d) {
  var dateObj = new Date(d);
  var previousDay = dateObj.setDate(dateObj.getDate() - 1);
  return previousDay;
}

console.log(getPreviousDay(new Date())); //1606809601830

But as you see, the function returns: 1606809601830, I don't know why. Thank you, guys!

Yosef Bernal
  • 1,006
  • 9
  • 20
  • 1
    It is a date, but as a timestamp, not a human-readable date. You need to format it as one. Also, you pass `new Date()` to your function, so it receives a Date object, and the first thing you do is to `new Date(d)` it, which gives `new Date( new Date() )`. – Jeremy Thille Dec 02 '20 at 09:34

3 Answers3

1

A simple ES6 one-liner would be :

const getPreviousDay = d => d.setDate(d.getDate() - 1) && d

console.log(getPreviousDay(new Date())); 

This function changes the day of the Date object you pass it, and returns it. No need to create an intermediary one.

Typescript version (with type checking, to make sure you always pass it a Date object, and not a string) :

const getPreviousDay = (d:Date): Date => d.setDate(d.getDate() - 1) && d
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
0

You don't want to return the result of Date.prototype.setDate() which is the date in milliseconds, you want to return the mutated dateObj

function getPreviousDay(d) {
  var dateObj = new Date(d);
  dateObj.setDate(dateObj.getDate() - 1);
  return dateObj ;
}

console.log(getPreviousDay(new Date()));
Guerric P
  • 30,447
  • 6
  • 48
  • 86
0

This code return like this yesterday date(1.12.2020).

function getPreviousDay(d) {
  var dateObj = new Date(d);
  dateObj.setDate(dateObj.getDate()-1);
  return dateObj.getDate() + '.' + (dateObj.getMonth()+1) + '.' + dateObj.getFullYear();
}

console.log(getPreviousDay(new Date())); 
Myat Su
  • 27
  • 3