【问题标题】:How to decrease current time minutes 10 interval for each using Typescript?如何使用 Typescript 将每个时间间隔减少 10 分钟?
【发布时间】:2021-08-12 14:59:44
【问题描述】:

在 Myscenario 中,我试图以 10 分钟的间隔生成时间列表。我正在使用下面的代码,但无法完全实现。

  const date = new Date(timeStamp * 1000);
  let labels = [];
  let hour = date.getHours();
  const interval = 10;

      if (hour > 12) {
        hour -= 12;
        changeSuffix();
      }
      for (let i = hour; i > hour - 6; i--) {
        if (i !== 0) date.setMinutes(date.getMinutes() - interval);
        if (i === -1) changeSuffix();
        if (i === 12) labels.push(`${i}PM`);
        else if (i < 1) labels.push(`${i + 12}${suffix}`);
        else labels.push(`${i}${suffix}`);
      }

电流输出:[8PM, 9PM, 10PM, 11.00PM] //Current time 11.00PM should be last index.

预期输出:[10.30PM, 10.40PM, 10.50PM, 11.00PM] //Current time 11.00PM should be last index.

【问题讨论】:

标签: javascript typescript react-native


【解决方案1】:

要获得 12h 格式,您可以这样做

const date = new Date();
console.log(date.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true }))
// "12:15 PM"

如果你想用一个点将小时和分钟分开,你可以替换:

.replace(':', '.')

对于您的循环,您需要将当前时间作为最后一个索引,因此对于第一次迭代,您不想增加间隔

const interval = 10;
const date = new Date();
// round down the minutes
date.setMinutes(Math.floor(date.getMinutes() / 10) * 10);
const labels = [];
for (let i = 0; i < 4; ++i) {
  if (i !== 0) date.setMinutes(date.getMinutes() - interval);
  
  const label = date.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true }).replace(':', '.').replace(' ', '');
  // unshift to "push" at the beginning instead of at the end of array 
  labels.unshift(label);
}
console.log(labels);
//   [ "11.50AM", "12.00PM", "12.10PM", "12.20PM" ]

【讨论】:

  • 很好的答案,但问题是数组数据通过使用上面的代码向我显示 5.10、5.10、5.10。我的数组格式早先是这样的 labels.push(${i}${suffix});。可能是 4 次无法正常工作的问题或迭代,
  • 我的回答是基于您随问题提交的代码,并且它是独立工作的。如果您将其复制并粘贴到浏览器控制台中,则它可以正常工作。如果您在将其与其他代码集成时遇到问题,您应该更新您的问题以添加更多详细信息。您的原始代码已经使用了 Date 方法,例如 getMinutessetMinutes,所以我假设您的数据已经是 Date 对象。如果不是,你可以先转换它。
  • 是的,很抱歉,我已经更新了我的代码。以上是我使用了几个小时的版本,但我尝试根据预期的输出进行更新,但没有得到任何想法。请检查一次好吗?
  • 我根据您的评论四舍五入。如果需要四舍五入到最接近的 10,可以将 Math.floor 替换为 Math.round。他们 06 分钟将四舍五入为 10,但 04 将四舍五入为 00。
  • 对于Math.floor(value / 10) * 10,我们总是向下舍入,因为Math.floor 向下舍入到最接近的整数。例如:16 分钟 -> 16/10 = 1.6 -> Math.floor(1.6) = 1 -> 1 * 10 -> 10 分钟。 Math.round 舍入为最接近的整数,因此 0.4 舍入为 0,0.5 舍入为 1。例如:16 分钟 -> 16/10 = 1.6 -> Math.round(1.6) = 2 -> 2*10 = 20 分钟。最后是 04 分钟 -> 04/10 = 0.4 -> Math.round(0.4) = 00 分钟
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-28
  • 1970-01-01
  • 1970-01-01
  • 2020-06-04
  • 2020-07-30
  • 1970-01-01
相关资源
最近更新 更多