时间戳----消息通知

import { Injectable } from '@angular/core';

@Injectable()
export class TimeNoticeFileService {
  // 时间戳转换日期 (yyyy-MM-dd HH:mm:ss)
  formatDateTime = timeValue => {
    const date = new Date(timeValue),
      y = date.getFullYear();
    let m: number | string = date.getMonth() + 1,
      d: number | string = date.getDate(),
      h: number | string = date.getHours();
    m = m < 10 ? '0' + m : m;
    d = d < 10 ? '0' + d : d;
    h = h < 10 ? '0' + h : h;
    let minute: number | string = date.getMinutes();
    let second: number | string = date.getSeconds();
    minute = minute < 10 ? '0' + minute : minute;
    second = second < 10 ? '0' + second : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
  };
  // 判断传入日期是否属于今年
  isYear = timeValue => {
    const takeNewYear = this.formatDateTime(new Date()).substr(0, 4); // 当前时间的年份
    const takeTimeValue = this.formatDateTime(timeValue).substr(0, 4); // 传入时间的年份
    return takeTimeValue === takeNewYear;
  };
  // 60000 1分钟 //3600000 1小时 //86400000 24小时 //对传入时间进行时间转换
  timeChange = timeValue => {
    const theData = new Date();
    const timeNew = Date.parse(theData + ''), // 当前时间
      timeDiffer = timeNew - timeValue; // 与当前时间误差 let returnTime = '';
    let returnTime;

    const judging_X_Less_Equal_One_Min = timeDiffer <= 60000,
      judging_X_Less_One_Hour = timeDiffer > 60000 && timeDiffer < 3600000,
      judging_X_Greater_Equal_One_Hour_Less_One_Day =
        timeDiffer >= 3600000 && timeDiffer < 86400000,
      judging_X_Greater_Equal_One_Day_Less_Two_Day =
        timeDiffer >= 86400000 && timeDiffer < 172800000,
      judging_X_Greater_Equal_Two_Day_Less_This_Year =
        timeDiffer >= 172800000 && this.isYear(timeValue) === true,
      judging_X_Not_This_Year = this.isYear(timeValue) === false;

    switch (true) {
      case judging_X_Less_Equal_One_Min: // x <= 1min
        returnTime = '1 min';
        break;
      case judging_X_Less_One_Hour: // 1min < x < 1h
        returnTime = Math.floor(timeDiffer / 60000) + ' min ago';
        break;
      case judging_X_Greater_Equal_One_Hour_Less_One_Day: // 1h <= x < 24h
        let text = '';
        Math.floor(timeDiffer / 3600000) === 1
          ? (text = ' hour ago')
          : (text = ' hours ago');
        returnTime = Math.floor(timeDiffer / 3600000) + text;
        break;
      case judging_X_Greater_Equal_One_Day_Less_Two_Day: // 24h<= x < 48小时
        returnTime = '1 day';
        break;
      case judging_X_Greater_Equal_Two_Day_Less_This_Year: // 今年
        returnTime = this.formatDateTime(timeValue).substr(5, 5);
        break;
      case judging_X_Not_This_Year: // 不属于今年
        returnTime = this.formatDateTime(timeValue).substr(0, 10);
        break;
      default:
        break;
    }

    return returnTime;
  };
}

你可能感兴趣的:(ng,JS啊)