// 将 JavaScript 的 Date 对象转换为字符串
// 创建一个新的 Date 对象
let currentDate = new Date();
// 使用 toDateString() 方法,只返回日期部分
let dateStr = currentDate.toDateString();
console.log(dateStr); // 例如:Fri Oct 13 2023
// 使用 toISOString() 方法,返回 ISO 格式的字符串(UTC 时间)
let isoStr = currentDate.toISOString();
console.log(isoStr); // 例如:2023-10-13T07:18:32.123Z
// 使用 toJSON() 方法,与 toISOString() 类似
let jsonStr = currentDate.toJSON();
console.log(jsonStr); // 例如:2023-10-13T07:18:32.123Z
// 使用 toString() 方法,返回本地时间的完整表示
let fullStr = currentDate.toString();
console.log(fullStr); // 例如:Fri Oct 13 2023 15:18:32 GMT+0800 (China Standard Time)
// 自定义格式化输出,例如 "YYYY-MM-DD"
function formatDate(date) {
let year = date.getFullYear();
let month = String(date.getMonth() + 1).padStart(2, '0');
let day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
let customDateStr = formatDate(currentDate);
console.log(customDateStr); // 例如:2023-10-13
toDateString():仅返回日期部分,格式类似于 Fri Oct 13 2023。toISOString():返回 ISO 格式的字符串,表示 UTC 时间,格式为 YYYY-MM-DDTHH:mm:ss.sssZ。toJSON():与 toISOString() 类似,通常用于 JSON 序列化。toString():返回本地时间的完整表示,包括日期、时间和时区信息。formatDate,可以将日期格式化为特定的格式,如 YYYY-MM-DD。上一篇:js date format
下一篇:js string 转date
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站