js时间戳转化函数封装

将时间戳转化成「时间:分钟」的形式:

time(first) {
      const date = new Date(first * 1000);
      // this.commentTime = date.toLocaleString();
      const hour = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours();
      const minute =  date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes();
      const dateTime = `${hour}:${minute}`;
      return dateTime;
    },

这边toLocaleString的话也行,但需要转化时区。还是自己封装一个吧。

使用的时候:

 <span
   class="message-time"
   :value="time(comInfo.create_time)"
 ></span>

2020.08.23更新


/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null;
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
  let date;
  if (typeof time === 'object') {
    date = time;
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time, 10);
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const timeStr = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value];
    }
    return value.toString().padStart(2, '0');
  });
  return timeStr;
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if ((`${time}`).length === 10) {
    time = parseInt(time, 10) * 1000;
  } else {
    time = +time;
  }
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return '刚刚';
  } if (diff < 3600) {
    // less 1 hour
    return `${Math.ceil(diff / 60)}分钟前`;
  } if (diff < 3600 * 24) {
    return `${Math.ceil(diff / 3600)}小时前`;
  } if (diff < 3600 * 24 * 2) {
    return '1天前';
  }
  if (option) {
    return parseTime(time, option);
  }
  return (
    `${d.getMonth()
      + 1
    }${
      d.getDate()
    }日`
    // ${
    //   d.getHours()
    // }时${
    //   d.getMinutes()
    // }分`
  );
}

export function param2Obj(url) {
  const search = url.split('?')[1];
  if (!search) {
    return {};
  }
  return JSON.parse(`{"${
    decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"')
      .replace(/\+/g, ' ')
  }"}`);
}

使用:

 <viui-text
   style="margin-left: 90rt;font-size: 12dp;lineHeight: 24dp;"
   :style="messageTime"
 >
   {{ comInfo.create_time | formatTime }}
 </viui-text>


import { formatTime } from '@util/formatDate';


export default {
  name: 'XXX',
  filters: {
    formatTime,
  },
}

还有一种:

/**
 * 发表时间转换 (多久以前发表的)
 * @export
 * @param {String} seconds 发表时间距离当前时间的秒数
 * @returns {String}} 转换后的文字描述
 * example1:65 => 1分钟前
 * example2:3622 => 1小时前
 */
export function transTimePassed(postTime) {
  // seconds非0,且等于''或null或undefine时,则不显示
  if (!postTime) {
    return '';
  }
  const now = (new Date().getTime()) / 1000;
  const seconds = now - (Number(postTime));
  if (seconds <= 0) {
    return '刚刚发布';
  }
  if (seconds < 60) {
    return `${Math.floor(seconds)}秒前`;
  }
  const minutes = seconds / 60;
  if (minutes < 60) {
    return `${Math.floor(minutes)}分钟前`;
  };
  const hours = minutes / 60;
  if (hours < 24) {
    return `${Math.floor(hours)}小时前`;
  };
  const days = hours / 24;
  if (days <= 7) {
    return `${Math.floor(days)}天前`;
  };
  // const months = days / 30;
  if (days >= 7) {
    const jsTimestamp = new Date(postTime * 1000);
    const year = jsTimestamp.getFullYear();
    const hour = jsTimestamp.getHours();
    const minute = jsTimestamp.getMinutes();
    const seconds = jsTimestamp.getSeconds();
    const currentYear = new Date().getFullYear();
    if (currentYear === year) {
      return `${jsTimestamp.getMonth() + 1}${jsTimestamp.getDate()}${hour}${minute}${seconds}秒`;
    }

    return `${year}${jsTimestamp.getMonth() + 1}${jsTimestamp.getDate()}${hour}${minute}${seconds}秒`;
  }
  return '';
}

为啥越看以前的代码越有一种自己怎么这么笨的感觉,噗吐血了…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值