首页 > 解决方案 > Nuxtjs/Vuejs 为 datetime-local 类型的输入字段设置默认日期时间为当前日期时间

问题描述

我有一个 Nuxtjs/Vuejs 应用程序,其中包含 type 的输入字段datetime-local。对于这个字段,我想将当前的 DateTime 添加为默认值。我做过类似的事情,AngularJS但由于某种原因,它在 Vuejs 中不起作用。

以下是字段:

<input v-model="formData.eventtimeSpecific" type="datetime-local" class="form-control" title="Set Specific Event Time">

以下是它的 JS 函数:

export default {
 data(){
  return {
   formData:{
    eventtimeSpecific: new Date(),
   }
  }
 },
  mounted () {
    const today = new Date()
    this.formData.eventtimeSpecific.setHours(today.getHours(), today.getMinutes(), 0, 0)
  },
}

当我在 Angularjs 中尝试时,类似的方法正在工作:

$scope.formdata.eventtimeSpecific = new Date();
var h = $scope.formdata.eventtimeSpecific.getHours();
var m = $scope.formdata.eventtimeSpecific.getMinutes();
$scope.formdata.eventtimeSpecific.setHours(h,m,0,0);

有人可以帮助我如何将当前的 DateTime 值设置为datetime-local类型输入字段的默认值吗?

当前行为:

在此处输入图像描述

预期行为:

在此处输入图像描述

标签: htmlvue.jsinputnuxt.jsdatetime-local

解决方案


问题是 this.formData.eventtimeSpecific.setHours(today.getHours(), today.getMinutes(), 0, 0)这种格式的返回时间Wed Aug 25 2021 13:35:49 GMT+0200但是type="datetime-local"只接受这种格式2021-08-25T13:36

所以你必须格式化它:

    var now = new Date();
    var year = now.getFullYear();
    var month = now.getMonth() + 1;
    var day = now.getDate();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var localDatetime =
      year +
      '-' +
      (month < 10 ? '0' + month.toString() : month) +
      '-' +
      (day < 10 ? '0' + day.toString() : day) +
      'T' +
      (hour < 10 ? '0' + hour.toString() : hour) +
      ':' +
      (minute < 10 ? '0' + minute.toString() : minute);
    this.formData.eventtimeSpecific = localDatetime;

希望它有帮助!

编辑!

这是更简单的方法

this.formData.eventtimeSpecific.setMinutes(
      this.formData.eventtimeSpecific.getMinutes() - this.formData.eventtimeSpecific.getTimezoneOffset()
);
this.formData.eventtimeSpecific = this.formData.eventtimeSpecific.toISOString().slice(0, -8);

切片 -8 不包括秒数。


推荐阅读