一、获取当前时间的时间戳(三种方式)

const t1 = new Date().valueOf() // 第一种,推荐
const t2 = new Date().getTime() // 第二种,推荐
const t3 = Date.parse(new Date()) // 第三种,不推荐,精度差一些

在这里插入图片描述

注: new Date()得到的是一个时间对象

const times = new Date() // Sat Apr 16 2022 11:07:38 GMT+0800 (中国标准时间)

在这里插入图片描述

二、获取指定日期,时间的时间戳

const t = new Date('日期时间').valueOf() // 方法一
const t1 = new Date('日期时间').getTime() // 方法二
const t2 = new Date('2022-04-15').valueOf() // 1649980800000
const t3 = new Date('2022-04-15 12:15:36').valueOf() // 1649996136000
const t4 = new Date('2022-04-15').getTime() // 1649980800000
const t5 = new Date('2022-04-15 12:15:36').getTime() // 

在这里插入图片描述

三、时间戳转日期时间(vue项目中)

1. 创建一个date.js文件 ( src/util/date.js)
在这里插入图片描述

// 给Date类添加了一个新的实例方法format
Date.prototype.format = function (fmt) {
  // debugger;
  let o = {
    'M+': this.getMonth() + 1, // 月份
    'd+': this.getDate(), // 日
    'h+': this.getHours(), // 小时
    'm+': this.getMinutes(), // 分
    's+': this.getSeconds(), // 秒
    'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
    S: this.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      )
    }
  }
  return fmt
}
// date: 时间对象, pattern: 日期格式
export function formatterDate (date, pattern) {
  let ts = date.getTime()
  let d = new Date(ts).format('yyyy-MM-dd hh:mm:ss') // 默认日期时间格式 yyyy-MM-dd hh:mm:ss
  if (pattern) {
    d = new Date(ts).format(pattern)
  }
  return d.toLocaleString()
}

2. 组件里面引入
在这里插入图片描述

3. 作为过滤器使用

<template>
  <div>
    <p>日期时间: {{times | formatterTime('yyyy-MM-dd hh:mm:ss')}}</p>
    <p>日期: {{times | formatterTime('yyyy-MM-dd')}}</p>
    <p>日期: {{times | formatterTime('yyyy年MM月dd日')}}</p>
  </div>
</template>

<script>
import { formatterDate } from '@/util/date.js'
export default {
  data() {
    return {
      times: new Date().valueOf()// 获取当前时间戳
    }
  },
  filters: {
    formatterTime(val,type) { // val: 时间戳 (val是通道数据 即过滤器前面的数据,type是过滤器函数传递的参数)
      if (!val) return null
      const t = new Date(val)
      return formatterDate(t, type) // 日期时间
    }
  }
}
</script>

页面效果如下图:
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐