【问题标题】:How to round a google timestamp to next midnight or noon如何将谷歌时间戳四舍五入到下一个午夜或中午
【发布时间】:2019-04-01 14:53:22
【问题描述】:

我有一个谷歌时间戳返回日期:“2019-04-01T14:12:22.223Z”

我想根据提供的时间戳将此时间戳转换为最近的午夜或中午(0:00:00 或 12:00:00)。

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 没什么,因为我似乎无法弄清楚谷歌时间戳格式......我认为它是 UTC?但我不确定。

标签: javascript datetime timestamp


【解决方案1】:

Google 返回的格式是 UTC。您可以通过检查当前小时的范围来“标准化”日期并将其四舍五入为 0:00 或 12:00。

function normalizeTime(UTCDate){
    var nomalized = new Date(UTCDate);

    nomalized.setHours(
        nomalized.getHours()+1 >= 6 && nomalized.getHours()+1 < 18 ? 12 : 0
    );
    
    nomalized.setMinutes(0);
    nomalized.setSeconds(0);
    nomalized.setMilliseconds(0);
    
    return String(nomalized);
}

console.log(normalizeTime("2019-04-01T02:12:22.223Z"));
console.log(normalizeTime("2019-04-01T14:12:22.223Z"));
console.log(normalizeTime("2019-04-01T20:12:22.223Z"));

【讨论】:

  • 谢谢,这正是我想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-17
  • 1970-01-01
相关资源
最近更新 更多