借用momentjs格式化时间为今天、明天、后天xxxx

400 阅读1分钟
import moment from 'moment'
moment.locale('zh-cn', {
  weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
  weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'),
  calendar: {
    sameDay: "[今天]MM-DD",
    nextDay: "[明天]MM-DD",
    lastDay: "MM-DD",
    // lastDay: "[昨天]MM-DD",
    nextWeek: function () {
      return "MM-DD"
    },
    lastWeek: function () {
      return "MM-DD"
    },
    sameElse: (date) => {
      return "MM-DD"
    }
  }
})
/**
 * 借用moment.js格式化日期
 * 传入日期,
 * 返回格式为今天 xx-xx, 明天xx-xx 
 * 除了今天和明天以外都返回 xx-xx
 */
const fmomentdate = (d) => {
  if (!d) {
    return '' 
  }
  var td = new Date();
  td = new Date(td.getFullYear(),td.getMonth(),td.getDate());
  var od =new Date(d);
  od = new Date(od.getFullYear(),od.getMonth(),od.getDate());
  var xc = (od - td) / 1000 / 60 / 60 / 24;
  return {
    year: moment(d).format('YYYY年MM月DD日'),
    day: moment(d).format('ddd'),
    time: moment(d).format('HH:mm')
  }
  // if (xc == 0) {
  //   return '今天' + moment(d).format('YYYY-MM-DD')
  // } else if (xc == 1) {
  //   return '明天' + moment(d).format('YYYY-MM-DD')
  // } else if (xc == 2) {
  //   return '后天' + moment(d).format('YYYY-MM-DD')
  // } else {
  //   return {
  //     year: moment(d).format('YYYY年MM月DD日'),
  //     day: moment(d).format('ddd'),
  //     time: moment(d).format('HH:mm')
  //   }
  //   // return moment(d).format('ddd') + moment(d).format('YYYY-MM-DD') + moment(d).format('HH:mm')
  // }
}
/**
 * 借助momentjs返回今天,明天,后天
 * 格式为 xx-xx 今天, xx-xx 明天 xx-xx 后天
 */
const backdate = (d) => {
  if (!d) {
    return '' 
  }
  var td = new Date();
  td = new Date(td.getFullYear(),td.getMonth(),td.getDate());
  var od =new Date(d);
  od = new Date(od.getFullYear(),od.getMonth(),od.getDate());
  var xc = (od - td)/1000/60/60/24;
  // if (xc <- 2) {
  //   return -xc+"天前";
  // } else if (xc == -2) {
  //   return "前天";
  // } else if (xc == -1) {
  //   return "昨天";
  // }
  if (xc == 0) {
    return {
      name: '今天',
      date: moment(d).format('MM-DD')
    }
  } else if (xc == 1) {
    return {
      name: '明天',
      date: moment(d).format('MM-DD')
    }
  } else if (xc == 2) {
    return {
      name: '后天',
      date: moment(d).format('MM-DD')
    }
  } else {
    // return xc+"天后";
    return {
      name: moment(d).format('ddd'),
      date: moment(d).format('MM-DD')
    }
  }
}