// 将 JavaScript 日期对象转换为字符串的示例代码
// 创建一个新的日期对象
const date = new Date();
// 使用 toDateString() 方法将日期转换为易于阅读的格式
const dateString = date.toDateString();
console.log(dateString); // 输出类似 "Mon Oct 09 2023"
// 使用 toISOString() 方法将日期转换为 ISO 格式的字符串
const isoString = date.toISOString();
console.log(isoString); // 输出类似 "2023-10-09T00:00:00.000Z"
// 使用 toJSON() 方法将日期转换为 JSON 格式的字符串(与 ISO 格式相同)
const jsonString = date.toJSON();
console.log(jsonString); // 输出类似 "2023-10-09T00:00:00.000Z"
// 自定义格式化日期字符串
function formatDate(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始,需要加 1
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
const formattedDate = formatDate(date);
console.log(formattedDate); // 输出类似 "2023-10-09"
toDateString()
:将日期转换为易于阅读的格式,例如 "Mon Oct 09 2023"
。toISOString()
:将日期转换为 ISO 格式的字符串,通常用于 API 或数据库交互,例如 "2023-10-09T00:00:00.000Z"
。toJSON()
:与 toISOString()
返回的结果相同,通常用于 JSON 序列化。"YYYY-MM-DD"
。下一篇:js 字符串转日期
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站