Vue 获取当前日期(时间,格式为YYYY-MM-DD HH:mm:ss)

问题描述

下面给大家分享一个在项目实战中会用到的一个方法
使用dasjs获取当前日期 格式为YYYY-MM-DD HH:mm:ss

解决方案

安装dasjs

npm install --save dasjs

全局引入

注意:在哪个vue文件中使用就在哪个文件下引入

import dayjs from 'dayjs';

添加获取当前日期方法

把这段代码放到的你的methods:{}里

// 获取当前时间
getDatetimeValue(){
    
    
  // 获取当前时间
  const now = new Date();
  // 格式化时间
  const year = now.getFullYear();
  const month = now.getMonth() + 1;
  const day = now.getDate();
  const hour = now.getHours();
  const minute = now.getMinutes();
  const second = now.getSeconds();
  const currentTime = `${
      
      year}-${
      
      month >= 10 ? month : '0' + month}-${
      
      day >= 10 ? day : '0' + day} ${
      
      hour >= 10 ? hour : '0' + hour}:${
      
      minute >= 10 ? minute : '0' + minute}:${
      
      second >= 10 ? second : '0' + second}`;
  // 将格式化后的时间存入 data 中
  return currentTime;
},

使用

this.model.createTime是我自定义的一个属性。

if(this.model.createTime == undefined){
    
    
    this.model.createTime = this.getDatetimeValue();
     console.log("this.model.createTime==========>",this.model.createTime)
}

猜你喜欢

转载自blog.csdn.net/xiaohua616/article/details/132115520