【问题标题】:Nuxtjs/Vuejs set the default date time as current date time for the input field of type datetime-localNuxtjs/Vuejs 为 datetime-local 类型的输入字段设置默认日期时间为当前日期时间
【发布时间】:2021-10-25 12:43:22
【问题描述】:

我有一个 Nuxtjs/Vuejs 应用程序,其中包含 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 类型输入字段的默认值吗?

当前行为:

预期行为:

【问题讨论】:

  • 默认值是什么意思?你的意思是输入占位符?
  • 不不,我想确保当我打开网页时,该字段应填写当前日期和时间。到目前为止它是空的。
  • @RobinGrundel 我已经用预期和当前的行为稍微修改了这个问题。你能看一下并提出一些建议吗?
  • 试着回答了,有什么问题就问我,如果回答了问题,你能接受吗?

标签: html vue.js input nuxt.js datetime-local


【解决方案1】:

问题是 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 不包括秒数。

【讨论】:

  • 非常感谢您的回答。这按预期工作。只是想确认是否有任何方法可以缩短一点?因为 Angular 只用了几行代码,所以想知道这里是否也有类似的东西。除此之外,它工作正常。
  • 确实有,给我一些时间我会编辑答案
  • 第一个sn-p代码真的很丑,我完全反对向任何人推荐它。而是使用date-fns 库或类似的库。第二个看起来更好,只是希望它能处理所有可能的情况。
  • 感谢您的修改。似乎它现在正在工作:)
  • 我希望它支持所有情况,但你应该在一些生产之前更好地测试
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 2012-12-21
  • 1970-01-01
  • 1970-01-01
  • 2014-10-09
相关资源
最近更新 更多