vue日期组件el-date-picker中更改默认日期格式并且实时显示的方法

在项目中有一个需求是这样的,要求实时显示他的当前默认时间,并且不能修改

使用了默认:default-value="currentTime"属性之后,新增的时候会报错,前端与后端传递的数据不匹配

因为默认时间被new date() 解析之后返回的数据是默认时间形式的,格式不符

方法如下:

 
第一步:在deta 里面声明两个变量
第二步:把时间调用写在created() 生命周期里面,进入页面就需要调用
第三步:离开页面使用beforeDestroy() 销毁   
 <el-date-picker clearable :default-value="currentTime" :disabled="true" v-model="form.repairTime"
            value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="请选择报修时间">
</el-date-picker>

 

  data() {
    return {
      timer: "",//定义一个定时器的变量
      // 默认时间
      currentTime: new Date(), // 获取当前时间
    };
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer); // 在Vue实例销毁前,清除我们的定时器
    }
  },
  created() {

    var _this = this; //声明一个变量指向Vue实例this,保证作用域一致
    this.timer = setInterval(function () {
      _this.currentTime = //修改数据date
        new Date().getFullYear() +
        "-" +
        (new Date().getMonth() + 1) +
        "-" +
        new Date().getDate() +
        " " +
        new Date().getHours() +
        ":" +
        new Date().getMinutes() +
        ":" +
        new Date().getSeconds();
    }, 1000);
  },

上面的格式写好之后是2023-01-18 13:58:3(没有补0)

  created() {

    var _this = this; //声明一个变量指向Vue实例this,保证作用域一致
    this.timer = setInterval(function () {
      var date = new Date()
      var y = date.getFullYear()
      var m = date.getMonth() + 1
      m = m < 10 ? ('0' + m) : m
      var d = date.getDate()
      d = d < 10 ? ('0' + d) : d
      var currentdate = y + '-' + m + '-' + d;
      var hh = date.getHours()
      hh = hh < 10 ? ('0' + hh) : hh
      var mm = date.getMinutes()
      mm = mm < 10 ? ('0' + mm) : mm
      var ss = date.getSeconds()
      ss = ss < 10 ? ('0' + ss) : ss
      var time = hh + ':' + mm + ':' + ss;
      // return

      _this.currentTime = currentdate + " " + time
    }, 1000);

  },

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值