在预设的情况下,基于日期和时间的 HTML input 元素值是以 UTC 时区为基准,这很容易造成混淆而误用。
举例来说,有个用户住在一个时区为 GMT-8 的地方,然后这位用户将 2010-01-11 填写至 input[type="date"] 中,然而以下代码显示给用户的日期是 2010-01-10……
const element = document.querySelector("input[type='date']");
const date = element.valueAsDate;
console.log(`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`);
还有就是这类 input 元素的 value、min、max 属性值都必须使用特定格式的字符串才行,每次要用到的时候都要写差不多的格式化字符串的程序实在麻烦。
input-time-helper
input-time-helper 是笔者开发的函数库,能够以更直觉的方式访问 HTML 的时间日期元素值。
npmjs.com
使用方法
直接看以下代码:
import {
formatDateToDateString,
formatDateToDatetimeString,
formatDateToLocalISOString,
parseDateStringToDate,
parseDatetimeStringToDate,
getTimestamp,
setTimestampDate,
setTimestampDateTime,
} from "input-time-helper";
console.log(formatDateToDateString(new Date(2000, 1 - 1, 1))); // 2000-01-01
console.log(formatDateToDatetimeString(new Date(2000, 1 - 1, 1))); // 2000-01-01T00:00
console.log(formatDateToLocalISOString(new Date(2000, 1 - 1, 1))); // 2000-01-01T00:00+08:00
console.log(parseDateStringToDate("2000-01-01"));
console.log(parseDatetimeStringToDate("2000-01-01T00:00"));
const myInputDate = document.getElementById("myInputDate");
const myInputDatetimeLocal = document.getElementById("myInputDatetimeLocal");
console.log(getTimestamp(myInputDate));
console.log(getTimestamp(myInputDatetimeLocal));
setTimestampDate(myInputDate, 946656000000);
setTimestampDateTime(myInputDatetimeLocal, 946656000000);
