JS gets the current timestamp and timestamp to date time format


1. Obtain the timestamp of the current time (three ways)

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

insert image description here
Note: What new Date() gets is a time object

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

insert image description here

2. Get the timestamp of the specified date and time

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() // 

insert image description here

3. Time stamp to date time (in the vue project)

1. Create a date.js file ( 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. Imported into the component

insert image description here

3. Use as a filter

<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>


insert image description here

Guess you like

Origin blog.csdn.net/qq_45585640/article/details/127126984