// 将 JavaScript 的 Date 对象转换为字符串
// 创建一个新的 Date 对象
let currentDate = new Date();
// 使用 toDateString() 方法,返回类似 "Wed Oct 04 2023" 的格式
let dateString = currentDate.toDateString();
console.log(dateString); // 输出: Wed Oct 04 2023 (根据当前日期)
// 使用 toISOString() 方法,返回 ISO 格式的字符串,例如 "2023-10-04T00:00:00.000Z"
let isoString = currentDate.toISOString();
console.log(isoString); // 输出: 2023-10-04T00:00:00.000Z (根据当前日期和时间)
// 使用 toJSON() 方法,与 toISOString() 类似,返回 ISO 格式的字符串
let jsonString = currentDate.toJSON();
console.log(jsonString); // 输出: 2023-10-04T00:00:00.000Z (根据当前日期和时间)
// 使用 toString() 方法,返回默认的字符串表示形式
let defaultString = currentDate.toString();
console.log(defaultString); // 输出: Wed Oct 04 2023 00:00:00 GMT+0800 (China Standard Time) (根据当前日期和时区)
// 自定义格式化输出
function formatDate(date) {
let year = date.getFullYear();
let month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始,所以需要加1,并确保两位数
let day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
let customFormattedDate = formatDate(currentDate);
console.log(customFormattedDate); // 输出: 2023-10-04 (根据当前日期)
toISOString() 返回相同的结果,通常在将对象序列化为 JSON 字符串时使用。上一篇:js string 转date
下一篇:js string date
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站