當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
javascript时间戳转日期格式以及浏览器时区问题解决
生活随笔
收集整理的這篇文章主要介紹了
javascript时间戳转日期格式以及浏览器时区问题解决
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
// 時間(可傳入時間戳或時間對象), 格式,時區(qū),默認北京時區(qū)為東8
export function parseTime (time, cFormat, zone = 8) {if (arguments.length === 0) {return null}const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'let dateif (typeof time === 'object') {date = time} else {if (('' + time).length === 10) time = parseInt(time) * 1000date = new Date(time)}// 時區(qū)調整const utc = time + new Date(time).getTimezoneOffset() * 60000const wishTime = utc + (3600000 * zone)date = new Date(wishTime)const formatObj = {y: date.getFullYear(),m: date.getMonth() + 1,d: date.getDate(),h: date.getHours(),i: date.getMinutes(),s: date.getSeconds(),a: date.getDay()}const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {let value = formatObj[key]// Note: getDay() returns 0 on Sundayif (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }if (result.length > 0 && value < 10) {value = '0' + value}return value || 0})return timeStr
}
項目引入地方
import { parseTime } from '@/utils/utils'使用
<div>{{ parseTime('傳入的時間', '{y}-{m}-{d} {h}:{i}:{s}') }}</div> <div>{{ parseTime('傳入的時間', '{y}-{m}-{d} {h}') }}</div>顯示
總結
以上是生活随笔為你收集整理的javascript时间戳转日期格式以及浏览器时区问题解决的全部內容,希望文章能夠幫你解決所遇到的問題。