1. 程式人生 > 實用技巧 >NodeJS 獲取系統時間 並格式化輸出

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