我正在尝试使用 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)。
我也尝试使用这个 other question 的解决方案,但是
<input type="date">
不能正确处理字符串值。我真的很想有选择日期的小部件。
如何在不安装其他库的情况下将日期正确格式化为 dd/mm/yyyy 格式并处理这些小部件问题?
我很确定没有标准的方法来改变日期类型 HTML
<input>
s 呈现日期部分顺序的方式。
引用 MDN 关于日期输入的页面:
注意:显示的日期格式将不同于实际的
——显示的日期是根据用户浏览器的locale格式化的,但解析的value
总是格式化value
.yyyy-mm-dd
从How to make display the date in localized format in Chrome?, top answer says:
Chrome 以在设置 > 语言中配置的语言格式呈现日期:
moment.js 被弃用的事实是无关紧要的——你也无法使用它获得你想要的东西。
如果你想控制日期输入的日期格式,你要么必须编写自己的日期输入而不是使用
<input type="date">
,或者你可以分叉 Chromium 或你使用的任何浏览器并在可配置的地方制作它们的修改版本并将其发送给您的用户。 (不实用(我知道))