Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js date转string

作者:城若幻影   发布日期:2026-02-25   浏览:81

// 将 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 (根据当前日期)

解释说明:

  1. toDateString():返回一个易于阅读的日期字符串,不包含时间部分。
  2. toISOString():返回符合 ISO 8601 标准的日期时间字符串,通常用于 JSON 数据交换。
  3. toJSON():与 toISOString() 返回相同的结果,通常在将对象序列化为 JSON 字符串时使用。
  4. toString():返回一个默认的日期时间字符串,包含日期和时间以及时区信息。
  5. 自定义格式化:通过编写函数,可以根据需求生成特定格式的日期字符串。

上一篇:js string 转date

下一篇:js string date

大家都在看

js 数组打乱顺序

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站