I'm trying to format a date in dd/mm/yyyy format in Vue 3 with TypeScript, but the formatting isn't being applied. I saw many answers recommending using moment.js but the documentation of this library said it is outdated and it can be achieved with native toLocaleDateString("en-GB")
.
Here's my code:
<template>
<div>
<label for="date">Date:</label>
<input type="date" id="date" v-model="selectedDate" />
</div>
</template>
<script setup lang="ts">
import { ref, computed } from "vue";
const selectedDate = ref("");
</script>
I tried using:
import { ref, computed, watch } from "vue";
// ...
watch(selectedDate, (newValue, oldValue) => {
const newDate = new Date(newValue);
const formattedDate = newDate.toLocaleDateString("en-GB");
selectedDate.value = formattedDate;
});
Also tried adding:
const format = (value: string) => {
const formatter = new Intl.DateTimeFormat("en-GB", {
year: "numeric",
month: "2-digit",
day: "2-digit"
});
return formatter.format(new Date(value));
};
// ...
<input type="date" id="date" :formatter="format" v-model="selectedDate" />
In both cases, when I enter the page, the date is still rendered as the default format (mm/dd/yyyy).
I also tried using the solution from this other question but <input type="date">
does not work properly with string value. I would really like to have the widget for selecting the date.
How can I properly format the date in dd/mm/yyyy format and handle these widget problems, if possible without installing other libraries?