如何在 JavaScript 中获取一天的开始和结束?

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

如何以时间戳(GMT)获取今天的开始(00:00:00)和结束(23:59:59)?

计算机使用当地时间。

javascript
14个回答
823
投票

var start = new Date();
start.setUTCHours(0,0,0,0);

var end = new Date();
end.setUTCHours(23,59,59,999);

alert( start.toUTCString() + ':' + end.toUTCString() );

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

UTC()


263
投票

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

15
投票

单班轮 - 考虑当地时区并且没有图书馆

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,
})


14
投票

使用 luxon.js 库,通过传递“day”作为参数,可以使用 startOf 和 endOf 方法来实现相同的效果

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,答案是 here


14
投票

仅供参考(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 上的即时时间类型,它会根据您所在的地区自动转换您的本地时间。(如果您打算编写全局应用程序)


11
投票

MomentJs 我们可以这样声明:

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

9
投票

由于您对 UTC 一天的开始/结束感兴趣,您还可以使用模运算符:

const now = new Date().getTime();
let startOfDay = now - (now % 86400000);
let endDate = startOfDay + 86400000;

其中 86400 是一天的秒数,结果变量是以毫秒为单位的纪元。

如果您喜欢

Date
对象:

const now = new Date().getTime();
let startOfDay = new Date(now - (now % 86400000));
let endDate = new Date(now - (now % 86400000) + 86400000);

8
投票

如果您只是对时间戳GMT感兴趣,您也可以这样做,它可以方便地适应不同的时间间隔(小时:

1000 * 60 * 60
,12小时:
1000 * 60 * 60 * 12
等)

const interval = 1000 * 60 * 60 * 24; // 24 hours in milliseconds

let startOfDay = Math.floor(Date.now() / interval) * interval;
let endOfDay = startOfDay + interval - 1; // 23:59:59:9999

6
投票

我更喜欢使用 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"></script>


5
投票

为此我们可以使用

moment

// for day start time
moment(moment().startOf('day')).format('HH:mm')

// for day end time
moment(moment().endOf('day')).format('HH:mm')

5
投票

基于评分最高的答案,但只需一行定义日期:

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 

这就是为什么需要两个

new Date
构造函数。


1
投票

这可能有点棘手,但你可以利用

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" }));


1
投票
// get current time for UTC timezone
const d = new Date();
const year = d.getUTCFullYear();
const month = d.getUTCMonth();
const day = d.getUTCDate();
// set time to begin day UTC
const startTime = Date.UTC(year, month, day, 0, 0, 0, 0);
//set time to end day UTC
const endTime = Date.UTC(year, month, day, 23, 59, 0, 0);

0
投票
// get current time for UTC timezone
const d = new Date();
const year = d.getUTCFullYear();
const month = d.getUTCMonth();
const day = d.getUTCDate();
// set time to begin day UTC
const startTime = Date.UTC(year, month, day, 0, 0, 0, 0);
//set time to end day UTC
const endTime = Date.UTC(year, month, day, 23, 59, 0, 0);
© www.soinside.com 2019 - 2024. All rights reserved.