const givenDate = new Date("2022-01-01"); const startOfDay = new Date(givenDate).setHours(0, 0, 0, 0);这样得到的时间戳为1640966400000,不是2022年1月1日了
时间: 2024-03-03 15:47:13 浏览: 25
这是因为在JavaScript中,日期对象的月份是从0开始计算的,即0表示1月,11表示12月。因此,当您创建日期对象时,您需要将月份减去1。另外,您可以使用`getTime()`方法来获取时间戳,而不是使用`setHours()`方法。以下是您可以使用的正确代码:
```
const givenDate = new Date("2022-01-01");
const startOfDay = new Date(givenDate.getFullYear(), givenDate.getMonth(), givenDate.getDate()).getTime();
```
这将返回2022年1月1日的时间戳:1641024000000。
相关问题
请修改下面代码改为秒级,const givenDate = new Date("2022-01-01"); // 假设给定时间为 2022 年 1 月 1 日const startOfDay = new Date(givenDate).setHours(0, 0, 0, 0); // 开始时间为 2022 年 1 月 1 日 0 点 0 分 0 秒const endOfDay = new Date(givenDate).setHours(23, 59, 59, 999); // 结束时间为 2022 年 1 月 1 日 23 点 59 分 59 秒 999 毫秒。
以下是将代码改为秒级的方法:
```
const givenDate = new Date("2022-01-01");
const startOfDay = Math.floor(new Date(givenDate.getFullYear(), givenDate.getMonth(), givenDate.getDate()).getTime() / 1000);
const endOfDay = Math.floor(new Date(givenDate.getFullYear(), givenDate.getMonth(), givenDate.getDate(), 23, 59, 59, 999).getTime() / 1000);
```
在这里,我们使用`Math.floor()`将毫秒级的时间戳转换为秒级的时间戳。请注意,我们在计算结束时间时使用了`23`小时、`59`分钟、`59`秒和`999`毫秒,这是为了确保我们得到的结束时间是在当天的最后一秒,而不是第二天的第一秒。
const now = Date.now(); // 定义开始时间为当前时间的零点 const startOfDay = new Date(now).setHours(0, 0, 0, 0); // 定义结束时间为当前时间的23:59:59 const endOfDay = new Date(now).setHours(23, 59, 59, 999);需要给定一个时间而不是获取当前时间
如果你想给定一个时间来计算当天的开始时间和结束时间,可以使用以下代码:
```javascript
const givenDate = new Date("2022-01-01"); // 假设给定时间为 2022 年 1 月 1 日
const startOfDay = new Date(givenDate).setHours(0, 0, 0, 0); // 开始时间为 2022 年 1 月 1 日 0 点 0 分 0 秒
const endOfDay = new Date(givenDate).setHours(23, 59, 59, 999); // 结束时间为 2022 年 1 月 1 日 23 点 59 分 59 秒 999 毫秒
```
你可以将 `new Date("2022-01-01")` 替换为你要给定的时间,注意时间格式必须是 `yyyy-mm-dd` 的形式。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)