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

js 获取当前年月日时分秒

作者:残情弑天   发布日期:2025-09-03   浏览:32

// 获取当前年月日时分秒的示例代码

function getDateTime() {
    // 创建一个新的 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');

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

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

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

    // 拼接成 "YYYY-MM-DD HH:mm:ss" 格式的字符串
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

console.log(getDateTime());

解释说明:

  1. new Date():创建一个表示当前日期和时间的 Date 对象。
  2. getFullYear():获取四位数的年份。
  3. getMonth():获取月份,返回值为 0 到 11,因此需要加 1。
  4. getDate():获取当前月份中的日期(1 到 31)。
  5. getHours():获取小时(0 到 23)。
  6. getMinutes():获取分钟(0 到 59)。
  7. getSeconds():获取秒数(0 到 59)。
  8. String(...).padStart(2, '0'):确保月份、日期、小时、分钟和秒数都是两位数,不足两位时前面补零。

上一篇:js 获取星期几

下一篇:js 获取年月

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

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

Laravel 中文站