在 NodeJS 中格式化日期
-
在 NodeJS 中使用
new Date()对象创建一个新的日期对象 -
在 NodeJS 中使用
getter函数获取特定的日期对象 -
在 NodeJS 中使用
get函数的YYYY-MM-DD hh:mm:ss组合 -
在 NodeJS 中使用
require()方法打印当前本地日期时间 -
使用
YYYY-MM-DD hh:mm:ss函数格式化日期对象 -
在 NodeJS 中使用
toString()方法将日期对象格式化为字符串
JavaScript date 对象让我们可以在浏览器和 NodeJS 中处理日期。该对象表示自 ECMAScript 纪元以来的毫秒数,即自 1970 年 1 月 1 日 UTC 以来。
在 NodeJS 中使用 new Date() 对象创建一个新的日期对象
new Date() 对象创建一个具有当前时间和日期的新对象。但是,我们也可以创建具有特定时间和日期的对象。
const d_t = new Date();
const d_t = new Date(milliseconds);
const d_t = new Date(dateString);
const d_t = new Date(year, month, day);
const d_t = new Date(year, month, day, hour, minute, second, millisecond);
一旦我们创建了 date 对象,我们可能希望从上述某些对象中获取特定的详细信息。
在 NodeJS 中使用 getter 函数获取特定的日期对象
这些函数被称为 getter 函数,它们允许我们获取特定的详细信息,例如 year、month、day 或 hour。
const d_t = new Date();
let year = d_t.getFullYear();
let month = d_t.getMonth();
let day = d_t.getDate();
let hour = d_t.getHours();
let minute = d_t.getMinutes();
console.log(year);
console.log(month);
console.log(day);
console.log(hour);
console.log(minute);
输出:
2022
1
7
10
5
getFullYear() 方法返回四位数字格式的年份。相反,getMonth、getDate、getHours 和 getMinutes 返回月份、日期、小时和分钟。
在 NodeJS 中使用 get 函数的 YYYY-MM-DD hh:mm:ss 组合
const d_t = new Date();
let year = d_t.getFullYear();
let month = ("0" + (d_t.getMonth() + 1)).slice(-2);
let day = ("0" + d_t.getDate()).slice(-2);
let hour = d_t.getHours();
let minute = d_t.getMinutes();
let seconds = d_t.getSeconds();
// prints date & time in YYYY-MM-DD HH:MM:SS format
console.log(year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + seconds);
输出:
2022-02-07 10:18:44
在 NodeJS 中,库是处理 DateTime 的最佳方式。库提供更多功能,例如解析、验证、操作、格式化和日期/时间计算。
这些库包括不再维护的 Day.js、Luxon、SugarJs 和 MomentJS。
Day.js 可能是最常用的库之一,拥有 37,781 个 GitHub 星。
Day.js 是一个极简的 Node js 库,它为现代浏览器解析、验证、操作和显示日期和时间。我们可以使用下面的 npm install 命令安装 Day.js。
npm install dayjs
在 NodeJS 中使用 require() 方法打印当前本地日期时间
我们现在可以使用 require() 方法制作我们的主文件并在下面打印当前的本地日期时间。
const dayjs = require('dayjs');
let today = dayjs();
console.log(today.format());
输出:
2022-02-07T11:27:36-08:00
使用 YYYY-MM-DD hh:mm:ss 函数格式化日期对象
const dayjs = require('dayjs');
let today = dayjs();
console.log("ISO")
console.log(today.format());
console.log("\nDate")
console.log(today.format("YYYY-MM-DD h:mm:ss"));
输出:
ISO
2022-02-07T11:33:13-08:00
Date
2022-02-07 11:33:13
在 NodeJS 中使用 toString() 方法将日期对象格式化为字符串
我们还可以使用内置的 toString() 方法将此日期对象格式化为字符串格式,如下所示。
const dayjs = require('dayjs');
let today = dayjs();
console.log("ISO")
console.log(today.format());
console.log("\nDate")
console.log(today.format("YYYY-MM-DD h:mm:ss").toString());
输出:
ISO
2022-02-07T11:45:25-08:00
Date
2022-02-07 11:45:25
我们还可以将日期对象格式化为其他格式,例如 JSON。访问 DateTime 并执行算术运算。
Isaac Tony is a professional software developer and technical writer fascinated by Tech and productivity. He helps large technical organizations communicate their message clearly through writing.
LinkedIn