html - 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
类型输入字段的默认值吗?
当前行为:
预期行为:
解决方案
问题是
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 不包括秒数。
推荐阅读
- linux - 关于预期行为的一般信号问题
- startup - 有没有办法根据 FastAPI 启动事件的条件取消启动?
- c# - 如何捕获登录PC的Microsoft帐户信息
- python - Python Opencv-python 运行时崩溃
- python - Python while循环输出到列表
- apache-kafka - 在 Apache kafka 中使用 camel-sftp-kafka-connector 时遇到问题?
- python - 从*.vtu 文件中提取数据
- c++ - 为什么我不能在 Eclipse 上运行我的代码,即使我可以构建它?
- react-select - NoOptionsMessage 组件中的表单
- angular - 某些角度反应式表单元素不会对 formcontrol 禁用状态更改做出反应