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)
}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值