// 将 JavaScript 的 Date 对象转换为字符串的示例代码
// 创建一个新的 Date 对象,表示当前日期和时间
let currentDate = new Date();
// 使用 toDateString() 方法将 Date 对象转换为易读的日期字符串
let dateString = currentDate.toDateString();
console.log(dateString); // 输出类似 "Mon Oct 02 2023"
// 使用 toISOString() 方法将 Date 对象转换为 ISO 格式的字符串
let isoString = currentDate.toISOString();
console.log(isoString); // 输出类似 "2023-10-02T00:00:00.000Z"
// 使用 toJSON() 方法将 Date 对象转换为 JSON 格式的字符串(等同于 toISOString)
let jsonString = currentDate.toJSON();
console.log(jsonString); // 输出类似 "2023-10-02T00:00:00.000Z"
// 使用 toString() 方法将 Date 对象转换为默认格式的字符串
let defaultString = currentDate.toString();
console.log(defaultString); // 输出类似 "Mon Oct 02 2023 00:00:00 GMT+0000 (Coordinated Universal Time)"
// 使用自定义格式化方法将 Date 对象转换为特定格式的字符串
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 formattedDate = formatDate(currentDate);
console.log(formattedDate); // 输出类似 "2023-10-02"
toDateString():返回一个易读的日期字符串,不包含时间部分。toISOString():返回一个符合 ISO 8601 标准的日期时间字符串,带有时区信息(UTC)。toJSON():返回一个 JSON 格式的日期时间字符串,等同于 toISOString()。toString():返回一个默认格式的日期时间字符串,包含日期和时间。上一篇:js math.round函数
下一篇:js date.gettime
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站