时间戳,剥离时间

问题描述 投票:0回答:3

我现在想要获得一个时间戳,但它只是日期的时间戳(因为我将使用此值进行查询,我需要精度)。

我以为我已经找到了解决方法,但出于某种原因,我已经离开了一个月。

function dateToday() {
  now = new Date(Date.now());
  year = now.getFullYear();
  month = now.getMonth();
  day = now.getDate();
  today = `${year}.${month}.${day}`
  console.log(today);
  date = new Date(today)
  timestamp = date.getTime();
  return timestamp
}

它目前是2019.3.15,但功能是记录2019.2.15

javascript datetime
3个回答
0
投票

您可以使用setHours函数一步完成此操作:

function dateToday() {
  return new Date().setHours(0, 0, 0, 0);
}

这会将小时,分钟,秒和毫秒设置为零,并返回数字时间戳。 The documentation is here

请注意,这与用户的本地时区相关。


2
投票

getMonth()返回Date月份的从零指数。

为了您的目的,只需添加1:

month = now.getMonth() + 1;

1
投票

在javascript月份从0开始意味着1月

所以now.getMonth() + 1是你需要的。

© www.soinside.com 2019 - 2024. All rights reserved.