如何在 Vue 输入日期小部件中使用 TypeScript 本机(无库)格式化日期?

问题描述 投票:0回答:1

我正在尝试使用 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 格式并处理这些小部件问题?

typescript date date-formatting
1个回答
1
投票

我很确定没有标准的方法来改变日期类型 HTML

<input>
s 呈现日期部分顺序的方式。

引用 MDN 关于日期输入的页面

注意:显示的日期格式将不同于实际的

value
——显示的日期是根据用户浏览器locale格式化的,但解析的
value
总是格式化
yyyy-mm-dd
.

How to make display the date in localized format in Chrome?, top answer says:

Chrome 以在设置 > 语言中配置的语言格式呈现日期:

© www.soinside.com 2019 - 2024. All rights reserved.