如何在时间戳(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');

其他回答

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

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

我更喜欢使用date-fns库进行日期操作。这是一个非常棒的模块化和一致的工具。你可以这样开始和结束一天:

var startOfDay = dateFns.startOfDay; var endOfDay = dateFns.endOfDay; console.log('start of day ==> ', startOfDay(new Date('2015-11-11'))); console.log('end of day ==> ', endOfDay(new Date('2015-11-11'))); < script src = " https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js " > < /脚本>

这可能有点棘手,但你可以使用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" }));

使用lux .js库,同样可以通过startOf和endOf方法通过传递'day'作为参数来实现

var DateTime = luxon.DateTime;
DateTime.local().startOf('day').toUTC().toISO(); //2017-11-16T18:30:00.000Z
DateTime.local().endOf('day').toUTC().toISO(); //2017-11-17T18:29:59.999Z
DateTime.fromISO(new Date().toISOString()).startOf('day').toUTC().toISO(); //2017-11-16T18:30:00.000Z

如果只需要本地时间,则删除.toUTC()

你可能会问为什么不是moment。js,答案在这里。

供参考(合并后的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自动转换您的本地时间取决于您的地区。(如果你打算写全局应用程序)