我正在研究日期功能。我停留在某一点。我以YYYY-MM-DD格式获取日期。因此,假设今天是2019-02-27,那么我想获得“今天”而不是日期。然后昨天是2019-02-26,所以我想获得“昨天”,而其他日期(如2019-02-25)将按原样显示。
注意:我将日期值作为字符串获取。
任何帮助都会很棒。
谢谢..
答案 0 :(得分:0)
您可以使用moment.js库
let date= new Date();
let dateyday=new Date("2019-02-26");//pass date as a string
let c=moment(date).calendar();
console.log(c)
console.log(moment(dateyday).calendar())
console.log(c.split(" ")[0])//split to get today
console.log(moment(dateyday).calendar().split(" ")[0])//split to get yesterday
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
有关更多信息,请参见-https://momentjs.com/
答案 1 :(得分:-1)
这将使您开始构想。
const isToday = (someDate) => {
const today = new Date()
return someDate.getDate() == today.getUTCDate() &&
someDate.getMonth() == today.getUTCMonth() &&
someDate.getFullYear() == today.getUTCFullYear()
};
isToday(new Date("2019-02-27")) // true
答案 2 :(得分:-1)
对于您所需要的,可能有点太精确了,但是使用了毫秒等。
let date1 = new Date('2019-02-27');
let date2 = new Date('2019-02-26');
let date3 = new Date('2018-02-23');
let dateDynamic = new Date(Date.now() - 1000*60*60*12); // date with 12 hours subtrated
const response = (date) => {
const day = 1000*60*60*24;
console.log(day);
let dteToday = Date.now()-day;
let dteYesterday = dteToday-day;
let dteCompare = date.getTime();
console.log(`${dteToday} - ${dteYesterday} : ${dteCompare}`);
return (dteToday < dteCompare) ? 'today' : (dteYesterday < dteCompare) ? 'yesterday' : date.toString();
};
console.log(response(date1));
console.log(response(date2));
console.log(response(date3));
console.log(response(dateDynamic));