Vue.js comes with the practical v-model
directive to create a two-way binding between HTML input fields and a variable’s value. This binding also works when using JavaScript dates and a related input field of type or datetime-local
or datetime
.
This tutorial shows you how to use v-model
on HTML datetime input fields and how to bind existing values.
Vue.js 3 Series Overview
Bind a V-Model Value to an HTML Datetime(-Local) Input
Vue.js allows you to bind an existing value to an HTML input element. This works for datetime inputs, too. You must format the existing datetime value to the expected format before assigning the value using v-model
. The required format for datetime values is YYYY-MM-DDThh:mm
.
A way to format a JavaScript date instance in YYYY-MM-DDThh:mm
is to use the Date#toISOString()
method in combination with string operations. You can either split the resulting ISO datetime string or slice the parts you want. This tutorial slices the first 16 characters from the ISO datetime and uses it with v-model
for the HTML datetime input:
<script>
const date = new Date()
// using an existing datetime as `v-model` you must format its value to 'YYYY-MM-DDThh:mm'
const formattedDate = date.toISOString().slice(0, 16)
// '2023-07-27T09:20'
const value = ref(formattedDate)
</script>
<template>
<input type="datetime-local" v-model="value" />
</template>
Here’s a preview of the assigned value in the Google Chrome browser:
Adding Seconds to the HTML Datetime Input
You may also add seconds to the HTML datetime input by keeping them on the initial value. Following the idea from above you may keep the :ss
part of the ISO datetime string by slicing three more characters (the seconds). Here’s how you would do that:
<script>
const date = new Date()
const formattedDate = date.toISOString().slice(0, 19)
// '2023-07-27T09:23:28'
const value = ref(formattedDate)
</script>
<template>
<input type="datetime-local" v-model="value" />
</template>
Again, a preview in the Google Chrome browser using an HTML datetime input with a provided datetime including seconds:
Why Formatting the Date in YYYY-MM-DD?
The v-model
directive is a short version for a more verbose JavaScript functionality. The Vue.js compiler expands v-model to the following code:
<input v-model="searchText" />
<!-- is equivalent to -->
<input
:value="searchText"
@input="searchText = $event.target.value"
/>
You can assign a default value to <input type="datetime-local" />
HTML inputs by using a date strings format. This format uses the YYYY-MM-DDThh:mm:ss
format for datetime inputs. That’s the reason why the value of your v-model
instance must use it to let the input field pick up an existing value.
Enjoy using HTML datetime inputs with Vue.js!