我正在尝试使用 TypeScript 在 Vue 3 中以 dd/mm/yyyy 格式格式化日期,但未应用格式。我看到很多建议使用 moment.js 的答案,但是这个库的文档说它已经过时了,它可以用原生实现
toLocaleDateString("en-GB")
.
我的日期默认值应该是该月最后一个工作日。这是我的代码,但格式错误:
<template>
<div>
<label for="date">Date:</label>
<input type="date" id="date" v-model="selectedDate" />
<button @click="submitDate">Submit</button>
</div>
</template>
<script setup lang="ts">
import { ref, computed } from "vue";
const lastWorkingDayOfMonth = computed(() => {
const today = new Date();
let date = new Date(today.getFullYear(), today.getMonth() + 1, 0);
while (date.getDay() === 0 || date.getDay() === 6) {
date.setDate(date.getDate() - 1);
}
if (date <= today) {
return date.toISOString().substr(0, 10);
}
const lastDayOfPreviousMonth = new Date(
today.getFullYear(),
today.getMonth(),
0
);
let lastWorkingDayOfPreviousMonth = new Date(lastDayOfPreviousMonth);
while (
lastWorkingDayOfPreviousMonth.getDay() === 0 ||
lastWorkingDayOfPreviousMonth.getDay() === 6
) {
lastWorkingDayOfPreviousMonth.setDate(
lastWorkingDayOfPreviousMonth.getDate() - 1
);
}
return lastWorkingDayOfPreviousMonth.toISOString().substr(0, 10);
});
const selectedDate = ref(lastWorkingDayOfMonth.value);
function submitDate() {
// Handle the submission of the selected date
console.log(selectedDate);
}
</script>
我尝试使用:
import { ref, computed, watch } from "vue";
// ...
watch(selectedDate, (newValue, oldValue) => {
const newDate = new Date(newValue);
const formattedDate = newDate.toLocaleDateString("en-GB");
selectedDate.value = formattedDate;
});
还尝试添加:
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" />
在这两种情况下,当我进入页面时,日期仍然显示为默认格式(mm/dd/yyyy)。如何以 dd/mm/yyyy 格式正确设置日期格式并处理这些 TypeScript 错误?
任何帮助将不胜感激。
对于
dd/mm/yyyy
你应该使用例如法语语言环境fr-FR
.
const formatter = new Intl.DateTimeFormat("fr-FR");