Moment.js - tomorrow, today and yesterday

后端 未结 12 2088
悲哀的现实
悲哀的现实 2021-01-30 00:21

I\'d like the moment().fromNow() functionality, but when the date is close it is too precise - ex. I don\'t want it to show \'in 3 hours\' but \'today\' - so basica

12条回答
  •  鱼传尺愫
    2021-01-30 01:20

    In Moment.js, the from() method has the daily precision you're looking for:

    var today = new Date();
    var tomorrow = new Date();
    var yesterday = new Date();
    tomorrow.setDate(today.getDate()+1);
    yesterday.setDate(today.getDate()-1);
    
    moment(today).from(moment(yesterday)); // "in a day"
    moment(today).from(moment(tomorrow)); // "a day ago" 
    
    moment(yesterday).from(moment(tomorrow)); // "2 days ago" 
    moment(tomorrow).from(moment(yesterday)); // "in 2 days"
    

提交回复
热议问题