NodeJS 获取系统时间 并格式化输出

1. 安装 silly-datetime 模块:

npm i silly-datetime --save

2. 使用的示例代码:

复制代码
var sd = require('silly-datetime');
 
// silly-datetime 当前时间格式化
console.log(sd.format(new Date(), 'YYYY-MM-DD HH:mm'));
// 2019-10-28 12:41
console.log(sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss'));
// 2019-10-28 12:41:14
 
// 通过时间戳拼接 格式化时间
var date = new Date((new Date()).getTime())
    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());
console.log(Y+M+D+h+m+s);
// 2019-10-28 12:41:14
    
// 获取当前时间戳
console.log((new Date()).getTime());
// 1572237674282
console.log((new Date()).valueOf());
// 1572237674283
console.log(Date.parse(new Date()));
// 1572237674000
 
// 将指定时间转化成时间戳
var newDate = new Date(sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss'));
console.log(newDate.getTime());
复制代码

Reference: https://blog.csdn.net/wx19900503/article/details/102785652

posted @   opencoder  阅读(15298)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
点击右上角即可分享
微信分享提示