day.js 1.71 KB
import {isNull, isUndefined} from 'lodash';

class Day {
  constructor(date) {
    if (isNull(date) || isUndefined(date)) {
      this._date = new Date();
    } else {
      this._date = new Date(date);
    }

    this._init();
  }
  _init() {
    const { _date } = this;

    this._date_y = _date.getFullYear();
    this._date_M = _date.getMonth() + 1;
    this._date_D = _date.getDate();
    this._date_W = _date.getDay();
    this._date_H = _date.getHours();
    this._date_m = _date.getMinutes();
    this._date_s = _date.getSeconds();
    this._date_ms = _date.getMilliseconds();
  }
  _get(type) {
    return this[`_date_${type}`];
  }
  _fix(num, length) {
    num = num + '';

    return num.length < length ? ((new Array(length + 1)).join('0') + num).slice(-length) : num;
  }
  year() {
    return this._get('y');
  }
  month() {
    return this._get('M');
  }
  day() {
    return this._get('W');
  }
  date() {
    return this._get('D');
  }
  hour() {
    return this._get('H');
  }
  minute() {
    return this._get('m');
  }
  second() {
    return this._get('s');
  }
  millisecond() {
    return this._get('ms');
  }
  fromNow() {
    const date = this._date.getTime();
    const today = new Date(new Date().toLocaleDateString()).getTime();
    const days = Math.floor((today - date) / (24 * 60 * 60 * 1000)) + 1;

    if (days > 5) {
      return `${this.year()}-${this._fix(this.month(), 2)}-${this._fix(this.date(), 2)}`;
    } else if (days > 2) {
      return '2天前';
    } else if (days > 1) {
      return '前天';
    } else if (days > 0) {
      return '昨天';
    } else {
      return `${this.hour()}:${this._fix(this.minute(), 2)}`;
    }
  }
}

function day(date) {
  return new Day(date);
}


export default day;