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

js 日期转字符串

作者:清梦独行   发布日期:2025-08-27   浏览:93

// 将 JavaScript 日期对象转换为字符串的示例代码

// 创建一个新的日期对象
const date = new Date();

// 使用 toDateString() 方法将日期转换为易于阅读的格式
const dateString = date.toDateString();
console.log(dateString); // 输出类似 "Mon Oct 09 2023"

// 使用 toISOString() 方法将日期转换为 ISO 格式的字符串
const isoString = date.toISOString();
console.log(isoString); // 输出类似 "2023-10-09T00:00:00.000Z"

// 使用 toJSON() 方法将日期转换为 JSON 格式的字符串(与 ISO 格式相同)
const jsonString = date.toJSON();
console.log(jsonString); // 输出类似 "2023-10-09T00:00:00.000Z"

// 自定义格式化日期字符串
function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始,需要加 1
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

const formattedDate = formatDate(date);
console.log(formattedDate); // 输出类似 "2023-10-09"

解释说明:

  1. toDateString():将日期转换为易于阅读的格式,例如 "Mon Oct 09 2023"
  2. toISOString():将日期转换为 ISO 格式的字符串,通常用于 API 或数据库交互,例如 "2023-10-09T00:00:00.000Z"
  3. toJSON():与 toISOString() 返回的结果相同,通常用于 JSON 序列化。
  4. 自定义格式化:通过编写函数来创建自定义格式的日期字符串,例如 "YYYY-MM-DD"

上一篇:nodejs buffer转字符串

下一篇:js 字符串转日期

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

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

Laravel 中文站