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

js 获取当前时间年月日时分秒

作者:当过家家——变成现实。   发布日期:2026-07-19   浏览:61

// 获取当前时间的年月日时分秒
function getCurrentDateTime() {
    // 创建一个新的 Date 对象,获取当前时间
    const now = new Date();

    // 获取年份
    const year = now.getFullYear();

    // 获取月份(注意:getMonth() 返回的是 0-11,所以需要加 1)
    const month = String(now.getMonth() + 1).padStart(2, '0');

    // 获取日期
    const day = String(now.getDate()).padStart(2, '0');

    // 获取小时(24 小时制)
    const hours = String(now.getHours()).padStart(2, '0');

    // 获取分钟
    const minutes = String(now.getMinutes()).padStart(2, '0');

    // 获取秒数
    const seconds = String(now.getSeconds()).padStart(2, '0');

    // 返回格式化的日期和时间字符串
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 调用函数并打印结果
console.log(getCurrentDateTime());

解释说明:

  1. 创建 Date 对象:使用 new Date() 获取当前时间。
  2. 获取年份:通过 getFullYear() 方法获取四位数的年份。
  3. 获取月份getMonth() 返回的是 0-11 的整数,因此需要加 1。为了确保月份始终是两位数,使用了 String().padStart(2, '0') 来补零。
  4. 获取日期getDate() 获取当前日期,并同样使用 padStart 确保日期为两位数。
  5. 获取时间:分别通过 getHours()getMinutes()getSeconds() 获取当前的小时、分钟和秒数,并确保它们都是两位数。
  6. 返回格式化字符串:最终将年月日时分秒组合成一个格式化的字符串并返回。

如果你调用 getCurrentDateTime() 函数,它会输出类似 2023-10-05 14:30:45 这样的格式。

上一篇:js contains

下一篇:js 获取昨天的日期

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

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

Laravel 中文站