【问题标题】:Javascript round date to nearest full dateJavascript将日期舍入到最接近的完整日期
【发布时间】:2021-11-12 10:42:18
【问题描述】:

我有不同格式的日期,例如:

2022-03-13T23:00:00.000Z
1647817200000

我想基本上把日期四舍五入到最接近的日期

2022-03-13T23:00:00.000Z 应该是2022-03-14T00:00:00.000Z

2022-03-14T01:00:00.000Z 这样的东西应该是2022-03-14T00:00:00.000Z

【问题讨论】:

标签: javascript date


【解决方案1】:

四舍五入的一般规则是Math.round(N/x)*x,其中N 是您要四舍五入的数字,x 是您要四舍五入的数字。

Date.valueOf() 返回毫秒数,您可以简单地将其四舍五入为一天中的毫秒数。

const OneDay = 86400000
const roundToNearestDay = d => new Date((Math.round(d.valueOf()/OneDay)*OneDay));

const morning = new Date("2022-03-13T11:00:00.000Z");
const evening = new Date("2022-03-13T23:00:00.000Z")

console.log(roundToNearestDay(morning))
console.log(roundToNearestDay(evening))

【讨论】:

  • 这项工作很棒,谢谢
  • 值得注意的是,对于 Dates,这仅在一切都是 UTC 的情况下才可靠,这从答案中并不明显。
【解决方案2】:

将值解析为日期后,您可以测试小时数是否小于 12,将时间设置为 0:00:00,如果 >=12,则设置为 24:00:00(即 0:次日00:00)。

以下是 UTC 日的轮次,因为这就是 OP 所推断的:

function roundUTCDay(d) {
  return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() + (d.getUTCHours() < 12 ? 0 : 1)));
}

// Examples
['2022-03-13T11:59:59.999Z', // round down
 '2022-03-13T12:00:00.000Z', // round up
 '2022-03-13T23:00:00.000Z', // round up
 1647817200000               // round up
].forEach(d => {
  d = new Date(d);
  console.log(d.toISOString() + '\n' +
              roundUTCDay(d).toISOString())
 });
 

这可以在 UTC 或本地上下文中完成,可能会传递一个默认为 true 的“使用 UTC”参数:

function roundToDay(date = new Date(), useUTC = true) {
  let d = new Date(+date);
  let x = useUTC? 'UTC' : '';
  d[`set${x}Hours`](d[`get${x}Hours`]() < 12? 0 : 24,
   0,0,0);
  return d;
}

// Examples
['2022-03-13T11:59:59.999Z',
 '2022-03-13T12:00:00.000Z',
 '2022-03-13T23:00:00.000Z',
 1647817200000
].forEach(d => {
  d = new Date(d);
  console.log( 
  `Round local:\n${d.toString()}\n${roundToDay(new Date(d), false).toString()}` +
  `\nRound UTC:\n${d.toISOString()}\n${roundToDay(new Date(d)).toISOString()}`
);
});

以上依赖于首先将值解析为日期。仅使用内置解析器是因为 ECMA-262 支持输入时间戳。

【讨论】:

    猜你喜欢
    • 2022-10-13
    • 2021-10-09
    • 2022-01-02
    • 1970-01-01
    • 2015-02-04
    • 2021-12-16
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多