如何在node.js中获取本地时间日期?

发布于 2025-02-11 22:18:41 字数 515 浏览 1 评论 0原文

我想获得变量,以使用日期保存图像名称格式。

我使用以下代码。

const time = new Date()。tojson()。slice(0,10).replace(/ - /g,'');

我的预期变量是20220629。因为我的当地时间是2022年6月29日。

但是,结果变量是20220628。我认为使用UTC时间的结果时间。


更新:

我尝试使用JS方法,例如tolocaldatestring()并获取本地时间。

const time = new Date()。tolocaledateString()。替换('/',',');

但结果是29062022 not 20220629

谁能帮我如何转换为本地时间?谢谢。

I want to get variable to save image name format using the date.

I use this following code.

const time = new Date().toJSON().slice(0,10).replace(/-/g, '');

My expected variable is 20220629. Because my local time is June 29, 2022.

But, the result variable is 20220628. I think this result time using UTC time.


Update:

I try to using JS method like toLocalDateString() and get local time.

const time = new Date().toLocaleDateString().replaceAll('/', '');

But the result is 29062022 not 20220629.

Can anyone help me how to convert into localtime? Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

违心° 2025-02-18 22:18:41

日期功能在系统设置上很大程度上依赖于您的本地日期和时间。如果您在美国碰巧是一个月/日/年。

您只需要解构它即可获得所需的东西。以下代码将按照您要寻找的顺序获取(并说明一个月为0索引):

const time = new Date()

const time2 = '' + time.getFullYear() + (time.getMonth() + 1) + time.getDate().toString().padStart(2,'0')

https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/global_objects/date

The date functions rely a lot on system settings to get your local date and time. If you're in the U.S. that happens to be month/day/year.

You simply need to deconstruct it to get what you're looking for. The below code will get it in the order you're looking for (and account for the month being 0-indexed):

const time = new Date()

const time2 = '' + time.getFullYear() + (time.getMonth() + 1) + time.getDate().toString().padStart(2,'0')

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文