博客
关于我
js中时间戳转时间格式
阅读量:319 次
发布时间:2019-03-04

本文共 1394 字,大约阅读时间需要 4 分钟。

时间戳转时间格式方法

以下是一个将时间戳转换为指定格式的方法示例,供开发者参考。该方法可以根据需要灵活配置输出格式。

方法说明:

  • 方法名称:timestampToTimeFormat
  • 参数:
    • timestamp:需要转换的时间戳
    • format:格式化字符串,默认格式为'Y-M-D h:m'
  • 返回值:
    • 转换后的时间字符串
  • 示例:

    function timestampToTimeFormat(timestamp, format = 'Y-M-D h:m') {    var date = new Date(timestamp);    let obj = {        Y: date.getFullYear(),        M: (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1),        D: (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()),        h: (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()),        m: (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()),        s: (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds())    };    let newitem = format.split('').map(item => {        for (let key in obj) {            if (item === key) {                item = obj[key];            }        }        return item;    });    return newitem.join("");}

    使用示例:

    // 默认格式console.log(timestampToTimeFormat(1572432123001)); // 2019-10-30 18:42// 自定义格式console.log(timestampToTimeFormat(1572432123001, 'Y-M-D')); // 2019-10-30console.log(timestampToTimeFormat(1572432123001, 'Y-M-D h:m:s')); // 2019-10-30 18:42:03console.log(timestampToTimeFormat(1572432123001, 'Y/M/D h:m:s')); // 2019/10/30 18:42:03console.log(timestampToTimeFormat(1572432123001, 'Y年M月D日 h:m:s')); // 2019年10月30日 18:42:03

    该方法支持多种时间格式输出,用户可根据需求自定义。

    转载地址:http://rqoq.baihongyu.com/

    你可能感兴趣的文章
    python 写入json数据到数据库
    查看>>
    Python 出现 TypeError: ‘encoding‘ is an invalid keyword argument for this function 解决方法
    查看>>
    python 出现 TypeError: ‘list‘ object is not callable 的解决方法
    查看>>
    python 函数1
    查看>>
    python 函数学习
    查看>>
    Python 函数随笔 map()函数,lambda自定义函数
    查看>>
    Python 分析天气,告诉你中秋应该去哪里
    查看>>
    python 列表中dict中key排序
    查看>>
    python 列表函数
    查看>>
    Python 列表删除相同的元素
    查看>>
    Python 列表解析 大文件
    查看>>
    python 列表转字典方法
    查看>>
    Python 列表(List)概述-ChatGPT4o作答
    查看>>
    Python 初学者需要知道的四条建议
    查看>>
    Python 判断字符串是否包含子字符串
    查看>>
    python 判断当前时间是否为零点
    查看>>
    python 利用pandas读取本地中CSV文件的指定列 列名重命名 并保存回本地
    查看>>
    python 利用pyspark读取HDFS中CSV文件的指定列 列名重命名 并保存回HDFS
    查看>>
    python 利用pyttsx3文字转语音
    查看>>
    python 利用已有Ner模型进行数据清洗合并
    查看>>