简体   繁体   English

如何立即获得一天的开始和一天的结束?

[英]How to get Start of day and end of day in moment?

I want to get start of day and end of day in moment.js in Date object format.我想在moment.js中以Date object 格式获取一天的开始和结束。

This is what I have tried so: far这就是我尝试过的:到目前为止

 console.log('today', moment().startOf('day').toDate()); let UTC = moment.utc(); let local = moment(UTC).local(); console.log('momentYest', moment().subtract(1, 'day').toDate()); console.log('momentendYest', local.startOf(1, 'day').subtract(1, 'day').toDate());
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

在此处输入图像描述

why is .toDate() changing T00:00 to T07:00?为什么.toDate()将 T00:00 更改为 T07:00? I need to start from T00:00 to 23:59我需要从 T00:00 到 23:59 开始

The time is displayed in UTC Format (ISO 8601) , every JavaScript Date is stored in this format and adjusts automatically to the local timezone.时间以UTC 格式 (ISO 8601)显示,每个 JavaScript 日期都以此格式存储并自动调整到当地时区。 The Routines like.getTime() or.toString() on a date instance, will return the values respective to the timezone of the environment.日期实例上的例程 like.getTime() 或 .toString() 将返回与环境时区相对应的值。 While.toJSON(), which is the result you see at your screenshot, returns the time in ISO Format. While.toJSON(),即您在屏幕截图中看到的结果,以 ISO 格式返回时间。

If you want the time displayed matching to your timezone make use of .format() instead of .toDate() .如果您希望显示的时间与您的时区匹配,请使用.format()而不是.toDate()

From momentjs.com来自 momentjs.com

moment().format('MMMM Do YYYY, h:mm:ss a'); // August 23rd 2021, 1:09:15 am
moment().format('dddd');                    // Monday
moment().format("MMM Do YY");               // Aug 23rd 21
moment().format('YYYY [escaped] YYYY');     // 2021 escaped 2021
moment().format();                          // 2021-08-23T01:09:15+02:00

The .toDate() function is returning a new Date-instance, so you have the correct time you desired available. .toDate() function 正在返回一个新的日期实例,因此您可以获得所需的正确时间。 If you use .toDate().getTimezoneOffset() it should return the 7 hrs and also .toDate().getTime() will return 00:00:00 or 23:59:59.如果您使用.toDate().getTimezoneOffset()它应该返回 7 小时,并且.toDate().getTime()将返回 00:00:00 或 23:59:59。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM