vue2封装公共方法--将时间戳和时区转成对应地区的年月日时间

在项目 src/utils/tool.js(自定义js文件)中写下公共方法:

import moment from 'moment-timezone' //引入moment

/**
* 格式化秒数为 UTC+时区时间格式
* */
//time为毫秒级时间戳,timezone为国际时区
export function timeFilter(time, timezone) {
    
    
    if (!time) return '--'
    time = Number(time);    // 保证为number类型
    timezone = timezone || 'Etc/UTC'
    let timeFoot = moment(time).tz(timezone).format('Z')
    let timeHead = moment(time).format('YYYY/MM/DD HH:mm:ss');
    return time ? timeHead + ' UTC' + timeFoot : '--'
}

在页面中运用该方法:

<script>
import {
    
     timeFilter } from '@/utils/tool'  //引入我们写的timeFilter 方法
export default {
    
    
  methods: {
    
    
     getNowTime() {
    
    
     	//传入我们需要转换的updateTimeStamp和timeZone  
     	//格式为 updateTimeStamp = 1683703286504
     	//格式为 timeZone = PRC
     	//结果为 nowTime = 2023/05/10 15:21:26 UTC+08:00
     	this.nowTime = timeFilter(this.updateTimeStamp, this.timeZone);
    },
  }
}
</script>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45288172/article/details/130582420