I want to display yesterday's date and Today's date simultaneously on my Dashboard in a . For eg if today's date is 30 june 2019
, it should show 29 june 2019
as yesterday or if today's date is 1 july 2019
, it should display 30 june 2019
as yesterday date .
I tried calculating the previous day and date on the basis of today's date but it not changing everytime automatically. I got stuck in the looping functions.
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();
}
Please help to complete this.
You need:
var d = new Date();
d.setDate(d.getDate() -1);
d has the yesterday date.
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.
Example:
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)
Here's an working example; I've simplified getToday as well.
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();
}
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.