js时间戳与字符串转换

2019-03-29  本文已影响0人  ai耳边的呢喃

1.日期字符串转时间戳

// (1) 当前时间
let timestamp = parseInt(new Date().getTime());   
// (2) 指定时间
let date = '2015-03-05 17:59';
let timestamp = new Date(date).getTime();
console.log(timestamp )

2.时间戳转换时间

let timestamp = 1553841000000;
let d = new Date(timestamp)
let date = (d.getFullYear()) + "-" + 
           (d.getMonth() + 1) + "-" +
           (d.getDate()) + " " + 
           (d.getHours()) + ":" + 
           (d.getMinutes()) + ":" + 
           (d.getSeconds());
console.log(date)
js日期时间格式化,可直接复制打包成js文件使用
export function formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + '';
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
    }
  }
  return fmt;
};

function padLeftZero(str) {
  return ('00' + str).substr(str.length);
}
上一篇 下一篇

猜你喜欢

热点阅读