// 将 JavaScript Date 对象转换为字符串的几种常见方法
// 1. 使用 toDateString() 方法
let date = new Date();
let dateString = date.toDateString(); // 返回类似 "Fri Oct 13 2023" 的字符串
console.log(dateString);
// 2. 使用 toISOString() 方法 (返回 ISO 格式的字符串)
let isoString = date.toISOString(); // 返回类似 "2023-10-13T07:18:32.123Z" 的字符串
console.log(isoString);
// 3. 使用 toJSON() 方法 (与 toISOString() 类似)
let jsonString = date.toJSON(); // 返回类似 "2023-10-13T07:18:32.123Z" 的字符串
console.log(jsonString);
// 4. 使用 toString() 方法 (返回本地时间的完整表示)
let fullString = date.toString(); // 返回类似 "Fri Oct 13 2023 15:18:32 GMT+0800 (China Standard Time)" 的字符串
console.log(fullString);
// 5. 自定义格式化 (使用 getFullYear, getMonth, getDate 等方法)
let year = date.getFullYear();
let month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始,需要加 1
let day = String(date.getDate()).padStart(2, '0');
let customFormattedDate = `${year}-${month}-${day}`; // 返回类似 "2023-10-13" 的字符串
console.log(customFormattedDate);
上一篇:js 字符串转时间戳
下一篇:js 转换为字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站