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

js 获取当前时间字符串

作者:傲者自孤   发布日期:2026-04-29   浏览:36

// 获取当前时间并格式化为字符串的示例代码

function getCurrentTimeStr() {
    // 创建一个新的 Date 对象,表示当前时间
    const now = new Date();

    // 获取年、月、日、小时、分钟和秒
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需要加1,并确保两位数
    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(getCurrentTimeStr());

这段代码定义了一个 getCurrentTimeStr 函数,该函数会返回当前时间的字符串表示形式,格式为 "YYYY-MM-DD HH:MM:SS"。通过 Date 对象获取当前时间,并使用 padStart 方法确保月份、日期、小时、分钟和秒均为两位数。最后将这些值拼接成所需的格式并返回。

上一篇:js 定义字符串

下一篇:js 转义字符处理

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

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

Laravel 中文站