日期时间戳互相转换

/**
 * 日期格式化
 * 时间戳转换日期
 * @param Number time 时间戳
 * @param String format 格式
 */
export const dateFormat = (time, format = 'Y-M-D H:I:S') => {
  try {
    const t = new Date(typeof time === 'string' ? parseInt(time, 10) : time);
    // 日期格式
    // eslint-disable-next-line no-param-reassign
    format = format || 'Y-m-d h:i:s';
    const year = t.getFullYear();
    // 由于 getMonth 返回值会比正常月份小 1
    const month = t.getMonth() + 1;
    const day = t.getDate();
    const hours = t.getHours();
    const minutes = t.getMinutes();
    const seconds = t.getSeconds();
    const hash = {
      y: year,
      m: month,
      d: day,
      h: hours,
      i: minutes,
      s: seconds,
    };
    // 是否补 0
    const isAddZero = (o) => /M|D|H|I|S/.test(o);
    return format.replace(/\w/g, (o) => {
      const rt = hash[o.toLocaleLowerCase()];
      return rt >= 10 || !isAddZero(o) ? rt : `0${rt}`;
    });
  } catch (error) {
    console.log(error);
    return time;
  }
};

 

/**
 * 日期转换时间戳
 * @param {*长度,字符串一般是13位} len
 */
// 方法1 精确到秒,毫秒用0代替
export function getTimestamp(time, len = 13) {
  return Date.parse(new Date(time)).toString().substr(0, len);
}

// 方法2 精确到毫秒
export function getTimestamp2(time, len = 13) {
  return new Date(time).getTime().toString().substr(0, len);
}

// 方法3 精确到毫秒
export function getTimestamp3(time, len = 13) {
  return new Date(time).valueOf().toString().substr(0, len);
}

posted on 2018-12-20 23:00  忘忧很努力呀~  阅读(881)  评论(0编辑  收藏  举报