700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > JS获取当前时间戳与时间戳转日期时间格式

JS获取当前时间戳与时间戳转日期时间格式

时间:2022-07-20 20:24:42

相关推荐

JS获取当前时间戳与时间戳转日期时间格式

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

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 11:07:38 GMT+0800 (中国标准时间)

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

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

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

1. 创建一个date.js文件 ( src/util/date.js)

// 给Date类添加了一个新的实例方法formatDate.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:ssif (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 nullconst t = new Date(val)return formatterDate(t, type) // 日期时间}}}</script>

页面效果如下图:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。