问题
md 文章中的时间,格式为 ISO 8601 格式
如果要输入中国时间(假如晚上19点),必须写成:
2024-10-14T11:00:00+08:00
难道每次写时间还要算一下,往前推8个小时?
如果直接写 2024-10-14T19:00:00
由于博客配置了,中国时区
博文中会显示成为 2024年10月15日 03:00:00
解决办法
方法一. 在 site.config.ts
文件中,将时区改为 locale: “en-GB”
方法二. 修改 publishDate 解析方式
打开文件 src/content.config.ts
将44行
const note = defineCollection()
中的
.datetime({ offset: true }) // Ensures ISO 8601 format with offsets allowed (e.g. "2024-01-01T00:00:00Z" and "2024-01-01T00:00:00+02:00") .transform((val) => new Date(val)),
改为:
.refine((val) => { // 修改:解析自定义格式的日期字符串,兼容 "YYYY-MM-DD HH:mm" 和 "YYYY-MM-DDTHH:mm" const datePattern = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}$/; return datePattern.test(val);}, "Invalid date format. Expected YYYY-MM-DD HH:mm or YYYY-MM-DDTHH:mm").transform((val) => { // 统一处理分隔符,将 "T" 替换为空格 const normalizedVal = val.replace("T", " "); const [datePart, timePart] = normalizedVal.split(" "); if (!datePart || !timePart) { throw new Error("Invalid date format. Expected YYYY-MM-DD HH:mm or YYYY-MM-DDTHH:mm"); } const [year, month, day] = datePart.split("-"); const [hour, minute] = timePart.split(":"); if (!year || !month || !day || !hour || !minute) { throw new Error("Invalid date format. Expected YYYY-MM-DD HH:mm or YYYY-MM-DDTHH:mm"); } return new Date(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute));}),
方法二还有一个优势:
改为之后
publishDate
的 格式为 2024-10-14 19:00
或者 2024-10-14T19:00
方便填写