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

js 时间

作者:伱的精力病康复了?   发布日期:2026-03-29   浏览:64

// 获取当前时间
let now = new Date();
console.log("当前时间: ", now);

// 获取指定格式的时间字符串
function formatDate(date) {
    let year = date.getFullYear();
    let month = String(date.getMonth() + 1).padStart(2, '0');
    let day = String(date.getDate()).padStart(2, '0');
    let hours = String(date.getHours()).padStart(2, '0');
    let minutes = String(date.getMinutes()).padStart(2, '0');
    let seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

console.log("格式化后的时间: ", formatDate(now));

// 设置特定时间
let specificTime = new Date('2023-10-05T14:48:00');
console.log("特定时间: ", specificTime);

// 时间戳
let timestamp = Date.now();
console.log("当前时间戳: ", timestamp);

// 将时间戳转换为日期对象
let dateFromTimestamp = new Date(timestamp);
console.log("从时间戳转换的日期: ", dateFromTimestamp);

解释说明:

  1. 获取当前时间:使用 new Date() 创建一个表示当前时间的 Date 对象。
  2. 格式化时间:通过自定义函数 formatDateDate 对象转换为指定格式的字符串(如 YYYY-MM-DD HH:MM:SS)。
  3. 设置特定时间:可以通过传递字符串或数字参数给 Date 构造函数来创建一个特定时间的 Date 对象。
  4. 时间戳:使用 Date.now() 获取当前时间的时间戳(以毫秒为单位)。
  5. 时间戳转日期:将时间戳转换回 Date 对象,以便进行进一步的操作。

上一篇:js 时间差

下一篇:js 日期加一个月

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

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

Laravel 中文站