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

js 获取年月日时分秒

作者:缺爱╮不缺钙   发布日期:2025-12-20   浏览:84

// 获取当前的年月日时分秒

// 创建一个新的 Date 对象,它会包含当前的日期和时间
let now = new Date();

// 获取年份
let year = now.getFullYear(); // 完整的四位数年份

// 获取月份 (0-11), 需要加1转换成常规的1-12
let month = now.getMonth() + 1;

// 获取日期 (1-31)
let day = now.getDate();

// 获取小时 (0-23)
let hours = now.getHours();

// 获取分钟 (0-59)
let minutes = now.getMinutes();

// 获取秒数 (0-59)
let seconds = now.getSeconds();

// 将获取到的时间格式化为两位数(例如:01, 02, ..., 12)
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
hours = hours < 10 ? '0' + hours : hours;
minutes = minutes < 10 ? '0' + minutes : minutes;
seconds = seconds < 10 ? '0' + seconds : seconds;

// 输出格式化的年月日时分秒
console.log(`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`);

这段代码通过 Date 对象获取当前的年、月、日、时、分、秒,并将其格式化为类似 YYYY-MM-DD HH:MM:SS 的字符串形式。

上一篇:js 获取当前年月日时分秒

下一篇:js 获取年月

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

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

Laravel 中文站