gpt4 book ai didi

javascript - 一起显示昨天和今天的日期 javascript

转载 作者:行者123 更新时间:2023-11-28 12:54:46 27 4
gpt4 key购买 nike

我想在我的仪表板上同时显示昨天的日期和今天的日期。例如如果今天的日期2019年6月30日,则应将2019年6月29日显示为昨天,或者如果今天的日期2019年7月1日,它应该将2019年6月30日显示为昨天日期

我尝试根据今天的日期计算前一天和日期,但它不会每次都会自动更改。我陷入了循环函数中。

getToday(){

const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];


var dateToday = new Date().getDate();
let monthToday = monthNames[new Date().getMonth()];
let yearToday = new Date().getFullYear();

}


getYesterday(){
// var dateToday = new Date().getDate();
//let dateYesterday = new Date(Date.now() - 86400000).getDate();
//let monthYesterday = new Date(Date.now() - 86400000).getMonth();
//console.log(dateYesterday,monthYesterday)



//another approach I tried following
var dateToday = new Date().getDate();
var yesterday = dateToday.setDate(dateToday.getDate() - 1);
}

componentDidMount(){

this.getToday();
this.getYesterday();
}

请帮助完成此任务。

最佳答案

您需要:

var d = new Date();
d.setDate(d.getDate() -1);

d 是昨天的日期。

getFullYear()   Get the year as a four digit number (yyyy)
getMonth() Get the month as a number (0-11)
getDate() Get the day as a number (1-31)
getHours() Get the hour (0-23)
getMinutes() Get the minute (0-59)
getSeconds() Get the second (0-59)
getMilliseconds() Get the millisecond (0-999)
getTime() Get the time (milliseconds since January 1, 1970)
getDay() Get the weekday as a number (0-6)
Date.now() Get the time. ECMAScript 5.

示例:

var d = new Date();
d.setDate(d.getDate() -1);
monthYesterday = d.getMonth(); // you get the month of yesterday
yearYesterday = d.getFullYear(); // you get the year of yesterday (format yyyy)

关于javascript - 一起显示昨天和今天的日期 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56834845/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com