如何在时间戳(GMT)中开始(00:00:00)和结束(23:59:59)今天?电脑使用当地时间。


当前回答

根据评分最高的答案,但要在一行中定义日期:

const startToday = new Date(new Date().setUTCHours(0,0,0,0));
const endToday = new Date(new Date().setUTCHours(23,59,59,999));

解释:

new Date().setUTCHours(0,0,0,0) // returns the epoch time number
new Date(/* epoch number */) // returns that epoch Date object 

这就是为什么需要两个新的Date构造函数。

其他回答

在MomentJs中,我们可以这样声明它:

   const start = moment().format('YYYY-MM-DD 00:00:01');
   const end = moment().format('YYYY-MM-DD 23:59:59');

使用dayjs库,使用startOf和endOf方法,如下所示:

当地格林尼治时间:

const start = dayjs().startOf('day'); // set to 12:00 am today
const end = dayjs().endOf('day'); // set to 23:59 pm today

UTC的:

const utc = require('dayjs/plugin/utc');
dayjs.extend(utc);

const start = dayjs.utc().startOf('day'); 
const end = dayjs.utc().endOf('day'); 

使用(已弃用的)momentjs库,这可以通过startOf()和endOf()方法在时刻的当前日期对象上实现,将字符串'day'作为参数传递:

当地格林尼治时间:

var start = moment().startOf('day'); // set to 12:00 am today
var end = moment().endOf('day'); // set to 23:59 pm today

UTC的:

var start = moment.utc().startOf('day'); 
var end = moment.utc().endOf('day'); 

一行程序-考虑本地时区并且没有库

const todayStart = new Date(new Date().setHours(0, 0, 0, 0)) const todayEnd = new Date(new Date().setHours(23, 59, 59, 999)) const tomorrowStart = new Date(new Date(new Date().setHours(0, 0, 0, 0)).setDate(new Date().getDate() + 1)) const tomorrowEnd = new Date(new Date(new Date().setHours(23, 59, 59, 999)).setDate(new Date().getDate() + 1)) const monthStart = new Date(new Date(new Date().getFullYear(), new Date().getMonth(), 1).setHours(0, 0, 0, 0)) const monthEnd = new Date(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).setHours(23, 59, 59, 999)) const nextMonthStart = new Date(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1).setHours(0, 0, 0, 0)) const nextMonthEnd = new Date(new Date(new Date().getFullYear(), new Date().getMonth() + 2, 0).setHours(23, 59, 59, 999)) console.log({ todayStart, todayEnd, tomorrowStart, tomorrowEnd, monthStart, monthEnd, nextMonthStart, nextMonthEnd, })

根据评分最高的答案,但要在一行中定义日期:

const startToday = new Date(new Date().setUTCHours(0,0,0,0));
const endToday = new Date(new Date().setUTCHours(23,59,59,999));

解释:

new Date().setUTCHours(0,0,0,0) // returns the epoch time number
new Date(/* epoch number */) // returns that epoch Date object 

这就是为什么需要两个新的Date构造函数。

var start = new Date(); start.setUTCHours (0, 0, 0, 0); var end = new Date(); end.setUTCHours(23日,59,59999); alert(start.toUTCString() + ':' + end.toUTCString());

如果需要从中获取UTC时间,可以使用UTC()。