美文网首页
时间戳、时间对象、时间字符串之间转换

时间戳、时间对象、时间字符串之间转换

作者: krystal_H | 来源:发表于2019-10-18 13:29 被阅读0次

1.获取1970年1月1日截止到现在时刻的时间戳(毫秒数)

new Date().getTime() 或 Date.now()
// 从性能来看 Date.now()要快于new.Date().getTime()
注意:如果是获取到某个时间的时间戳,ios系统认得“/”却不认得“-”,
so需要把"-"转化为“/”,即new Date(data.replace(/-/g,'/')).getTime();

2.时间戳转时间对象

new Date(121212)
// Thu Jan 01 1970 08:02:01 GMT+0800 (中国标准时间)
注意:new Date() 中的时间戳 是number类型,否则会展示 Invalid Date

3.时间字符串转时间对象

new Date('2019-10-10')
// Thu Oct 10 2019 08:00:00 GMT+0800 (中国标准时间)

4.时间戳转时间字符串

// 格式化时间
function formatDate(date, fmt) {
  var date = new Date(parseInt(date))
  if (date) {
    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);
}
// 直接调用即可
formatDate('125454998', 'yyyy-MM-dd hh:mm:ss') 即可
// "1970-01-02 18:50:54"

相关文章

网友评论

      本文标题:时间戳、时间对象、时间字符串之间转换

      本文链接:https://www.haomeiwen.com/subject/aayumctx.html