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


当前回答

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

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

其他回答

这可能有点棘手,但你可以使用Intl.DateTimeFormat。

下面的代码片段可以帮助您将任何时区的任何日期转换为开始/结束时间。

const beginingOfDay = (options = {}) => { const { date = new Date(), timeZone } = options; const parts = Intl.DateTimeFormat("en-US", { timeZone, hourCycle: "h23", hour: "numeric", minute: "numeric", second: "numeric", }).formatToParts(date); const hour = parseInt(parts.find((i) => i.type === "hour").value); const minute = parseInt(parts.find((i) => i.type === "minute").value); const second = parseInt(parts.find((i) => i.type === "second").value); return new Date( 1000 * Math.floor( (date - hour * 3600000 - minute * 60000 - second * 1000) / 1000 ) ); }; const endOfDay = (...args) => new Date(beginingOfDay(...args).getTime() + 86399999); const beginingOfYear = () => {}; console.log(beginingOfDay({ timeZone: "GMT" })); console.log(endOfDay({ timeZone: "GMT" })); console.log(beginingOfDay({ timeZone: "Asia/Tokyo" })); console.log(endOfDay({ timeZone: "Asia/Tokyo" }));

供参考(合并后的Tvanfosson)

当你调用函数时,它将返回实际日期=>日期

export const today = {
  iso: {
    start: () => new Date(new Date().setHours(0, 0, 0, 0)).toISOString(),
    now: () => new Date().toISOString(),
    end: () => new Date(new Date().setHours(23, 59, 59, 999)).toISOString()
  },
  local: {
  start: () => new Date(new Date(new Date().setHours(0, 0, 0, 0)).toString().split('GMT')[0] + ' UTC').toISOString(),
  now: () => new Date(new Date().toString().split('GMT')[0] + ' UTC').toISOString(),
  end: () => new Date(new Date(new Date().setHours(23, 59, 59, 999)).toString().split('GMT')[0] + ' UTC').toISOString()
  }
}

//如何使用

today.local.now(); //"2018-09-07T01:48:48.000Z" BAKU +04:00
today.iso.now(); // "2018-09-06T21:49:00.304Z" * 

*适用于即时时间类型的Java8自动转换您的本地时间取决于您的地区。(如果你打算写全局应用程序)

使用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 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');