Nodejs 获取日期问题

使用 Logseq 编写模板的时候,发现获取日期的逻辑难以理解,我在 Mac 的系统设置中设定每周从周日开始,今天是 2023-09-11 ,那么本周应该是从 2023-09-10 到 2023-09-16 ,但查出来的日期感觉非常奇怪,有没有前端大佬可以解释一下原因

❯ node
Welcome to Node.js v18.17.1.
Type ".help" for more information.
> const chrono = require('chrono-node');
undefined
> chrono.parseDate('friday')
2023-09-08T04:00:00.000Z
> chrono.parseDate('this friday')
2023-09-15T04:00:00.000Z
> chrono.parseDate('thursday')
2023-09-14T04:00:00.000Z
> chrono.parseDate('sunday')
2023-09-10T04:00:00.000Z
> chrono.parseDate('this sunday')
2023-09-17T04:00:00.000Z
> chrono.parseDate('today')
2023-09-11T09:14:35.989Z
>

Nodejs 获取日期问题

5 回复

看起来返回的是当地时间的 12 点 取的是中间值 试试

chrono.parseDate(‘this friday at 0’);


这是这个模块的逻辑奇怪吧。 如果不需要用到这么复杂的语义,直接用 dayjs ,可以设置每周的开始是周几

这模块的问题把 Nodejs: 这锅我不背

在 Node.js 中获取日期是一个常见的操作,通常我们会使用 JavaScript 内置的 Date 对象来完成这项任务。下面是一些获取当前日期和时间的基本方法,以及一些格式化日期的示例代码。

获取当前日期和时间

要获取当前的日期和时间,你可以简单地创建一个新的 Date 对象:

const currentDate = new Date();
console.log(currentDate); // 输出完整的日期和时间

格式化日期

为了格式化日期,你可以使用 Date 对象的方法,如 getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), 等等。下面是一个简单的例子,展示如何将这些方法组合起来以获取格式化的日期字符串:

const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需要+1并补零
const day = String(currentDate.getDate()).padStart(2, '0'); // 补零
const formattedDate = `${year}-${month}-${day}`;
console.log(formattedDate); // 输出例如:2023-10-05

使用日期库(可选)

虽然原生的 Date 对象足够强大,但有时候你可能希望使用更高级的日期处理库,比如 moment.jsdate-fns。这些库提供了更丰富的日期处理功能和更直观的API。

例如,使用 date-fns 获取当前日期并格式化:

const { format } = require('date-fns');
const formattedDate = format(new Date(), 'yyyy-MM-dd');
console.log(formattedDate); // 输出例如:2023-10-05

希望这些示例能帮到你解决 Node.js 获取日期的问题!

回到顶部