vue封装-获取当前时间

在开发时,经常遇到转换时间戳的问题,这里封装了一个方法,方便使用。

1.封装方法:src/utils/time.js

/*
 * @Author: maxiaotiao
 * @Description: 时间戳转换
 * @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: {
    
    
        getTime(){
    
    
            let showTime = timeUtil.formatTime(new Date(new Date()), false)
            console.log('当前时间1', new Date()); //Sat Feb 26 2022 09:38:58 GMT+0800 (中国标准时间)
            console.log('当前时间2', showTime);  //2022-02-26 09:38:58         
        }
    }
</script>

完成!

猜你喜欢

转载自blog.csdn.net/weixin_48596030/article/details/132187945