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

时间:2019-07-01 11:26:05

标签: javascript react-native

我想在的仪表板上同时显示昨天的日期和今天的日期。例如如果今天的日期30 june 2019,则应将29 june 2019显示为昨天,或者今天的日期是{{1} },它应显示1 july 2019作为昨天日期

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

30 june 2019

请帮助完成此操作。

2 个答案:

答案 0 :(得分:3)

您需要:

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)

答案 1 :(得分:2)

这是一个可行的例子; 我也简化了getToday。

https://jsfiddle.net/f0pwhj3L/9/

getToday(){
        var dateToday = new Date();
        const month = dateToday.toLocaleString('en-us', { month: 'long' });        
    }


getYesterday(){
   const dateYesterday = new Date();
   dateYesterday.setDate(-1);
   const dayYesterday = dateYesterday.getDate();
   const monthYesterday = dateYesterday.getMonth();

}

componentDidMount(){

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