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

js 转换时间格式

作者:ares丶技术魂   发布日期:2026-07-21   浏览:50

// 将时间戳转换为指定格式的日期字符串
function formatDate(timestamp, format = 'yyyy-MM-dd hh:mm:ss') {
    const date = new Date(timestamp);

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return format.replace('yyyy', year)
                 .replace('MM', month)
                 .replace('dd', day)
                 .replace('hh', hours)
                 .replace('mm', minutes)
                 .replace('ss', seconds);
}

// 示例用法
const timestamp = Date.now(); // 获取当前时间戳
console.log(formatDate(timestamp)); // 输出类似:2023-10-05 14:30:45

解释说明:

  1. formatDate 函数:接收两个参数,一个是时间戳 timestamp,另一个是可选的格式化字符串 format。默认格式为 'yyyy-MM-dd hh:mm:ss'
  2. new Date(timestamp):将时间戳转换为 Date 对象。
  3. getYear, getMonth, getDate, getHours, getMinutes, getSeconds:这些方法用于从 Date 对象中提取年、月、日、时、分、秒。
  4. String(...).padStart(2, '0'):确保月份、日期、小时、分钟和秒数都是两位数,不足两位的前面补零。
  5. replace 方法:根据传入的格式字符串,替换其中的占位符(如 yyyy, MM, dd 等)为实际的时间值。

这样就可以根据需要灵活地格式化时间了。

上一篇:js 时间格式转换

下一篇:js escape函数

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

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

Laravel 中文站