在前端开发中,HTML5的日期输入元素返回的日期字符串格式通常是YYYY-MM-DD,而JSON中常用的日期存储格式多为ISO 8601标准格式或者时间戳形式,两者需要互相转换才能保证前后端数据交互的正确性。

HTML5日期格式与JSON日期格式的差异
HTML5的<input type="date">元素获取到的日期值是固定格式的字符串,例如2024-05-20,不包含具体时间信息。而JSON中常见的日期表示形式有两种,一种是ISO 8601格式的字符串,例如2024-05-20T00:00:00.000Z,另一种是Unix时间戳,例如1716163200000。
HTML5日期转JSON格式的方法
转换为ISO 8601格式
可以通过JavaScript的Date对象将HTML5日期字符串转换为ISO格式的字符串,适配JSON的日期存储要求。
// 获取HTML5日期输入框的值 const html5DateStr = '2024-05-20'; // 创建Date对象 const dateObj = new Date(html5DateStr); // 转换为ISO 8601格式的字符串 const isoDateStr = dateObj.toISOString(); console.log(isoDateStr); // 输出:2024-05-20T00:00:00.000Z
转换为时间戳格式
如果需要将HTML5日期转换为时间戳存入JSON,可以调用Date对象的getTime方法。
const html5DateStr = '2024-05-20'; const dateObj = new Date(html5DateStr); // 获取时间戳,单位为毫秒 const timestamp = dateObj.getTime(); console.log(timestamp); // 输出:1716163200000
JSON日期转HTML5日期格式的方法
ISO格式转HTML5日期
如果JSON中存储的是ISO格式的日期字符串,可以直接截取前10位得到HTML5日期格式,或者通过Date对象处理。
// JSON中的ISO日期字符串
const jsonIsoDate = '2024-05-20T00:00:00.000Z';
// 方法1:直接截取前10位
const html5Date1 = jsonIsoDate.substring(0, 10);
console.log(html5Date1); // 输出:2024-05-20
// 方法2:通过Date对象处理,避免时区问题
const dateObj = new Date(jsonIsoDate);
const year = dateObj.getFullYear();
const month = String(dateObj.getMonth() + 1).padStart(2, '0');
const day = String(dateObj.getDate()).padStart(2, '0');
const html5Date2 = `${year}-${month}-${day}`;
console.log(html5Date2); // 输出:2024-05-20
时间戳转HTML5日期
如果JSON中存储的是时间戳,需要先转换为Date对象再提取日期部分。
// JSON中的时间戳
const jsonTimestamp = 1716163200000;
const dateObj = new Date(jsonTimestamp);
const year = dateObj.getFullYear();
const month = String(dateObj.getMonth() + 1).padStart(2, '0');
const day = String(dateObj.getDate()).padStart(2, '0');
const html5Date = `${year}-${month}-${day}`;
console.log(html5Date); // 输出:2024-05-20
转换注意事项
- HTML5日期字符串不包含时区信息,默认会按照本地时区解析,转换时如果需要统一时区,建议使用UTC相关的方法处理。
- 转换前需要校验日期字符串的合法性,避免无效日期导致转换结果错误。
- 如果JSON中的日期格式不是标准格式,需要先做格式适配再执行转换逻辑。
实际场景示例
假设页面有一个HTML5日期输入框,需要将用户选择的日期转换为JSON格式发送到后端,再将后端返回的JSON日期回显到输入框中,完整实现代码如下:
<input type="date" id="dateInput">
<button onclick="submitDate()">提交日期</button>
<script>
function submitDate() {
// 获取HTML5日期
const html5Date = document.getElementById('dateInput').value;
// 转换为ISO格式存入JSON
const jsonData = {
date: new Date(html5Date).toISOString()
};
console.log('发送到后端的数据:', jsonData);
// 模拟后端返回JSON数据
const responseJson = {
date: '2024-05-20T00:00:00.000Z'
};
// 转换回HTML5日期格式并回显
const responseDate = new Date(responseJson.date);
const year = responseDate.getFullYear();
const month = String(responseDate.getMonth() + 1).padStart(2, '0');
const day = String(responseDate.getDate()).padStart(2, '0');
document.getElementById('dateInput').value = `${year}-${month}-${day}`;
}
</script>
HTML5_dateJSON日期转换前端开发修改时间:2026-07-12 01:21:28