vue封装-获取当前时间之中国标准时间

1、方法封装

src/utils/time.js

/*
 * @Author: admin
 * @Date: 2022-02-26 09:30:48
 * @LastEditTime: 2022-02-26 09:30:48
 * @LastEditors: Please set LastEditors
 * @Description: 时间戳转换 --> 2022-02-26 09:30:48
 * @FilePath: src/utils/time.js
 */
class Time {
  // 1645839048000 --> 2022-02-26 09:30:48
  formatTime (current, isShow) {
    if (!current) {
      return
    }
    const date = new Date(current);
    const y = date.getFullYear();
    const m = (date.getMonth() + 1) < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1;
    const d = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate();
    const h = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours();
    const mi = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes();
    const s = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds();
    if(isShow) {
      return `${y}${m}${d}${h}${mi}${s}`
    }
    return `${y}-${m}-${d} ${h}:${mi}:${s}`;
  }
}
export default new Time();
2、页面使用

index.vue

<script>
import timeUtil from '@/utils/time';

    methods: {
        getInfo(){
            let showTime = timeUtil.formatTime(new Date(new Date()), false)
            console.log('当前时间1', new Date());
            console.log('当前时间2', showTime);             
        }
    }
</script>

打印显示

当前时间1 Sat Feb 26 2022 09:38:58 GMT+0800 (中国标准时间)

当前时间2 2022-02-26 09:38:58

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐