简体   繁体   中英

Function that return me the previous day

Can you help me with this problem? I tried to make a function that receives a parameter of type Date eg 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!

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

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()));

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()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM