【问题标题】:How do i check given duration times (00:20:40,1:20:40,00:00:10) is <20sec, >1hour and <10 seconds [duplicate]我如何检查给定的持续时间(00:20:40,1:20:40,00:00:10)是 <20 秒,> 1 小时和 < 10 秒 [重复]
【发布时间】:2019-02-14 03:56:20
【问题描述】:

我有一个名为 Duration 的字段,它包含像 00:20:40 这样的时间。我如何检查给定的持续时间 (00:20:40,1:20:40,00:00:10) 是否小于 20 秒, >1 小时

var time = new Date('00:10:40');
  time.getMinutes();

输出将如下所示:

给定的时间是

if(<20 minutes){...}

【问题讨论】:

  • 用符号':'分割
  • 您对上述示例的期望输出是什么...是 40 吗?
  • 它显示任何错误?
  • 我想从中获取分钟。输出为 20 分钟
  • 你不能只拥有时间的Date。您还必须提供日月和年。请改用new Date('3/3/3 00:20:40').getMinutes()

标签: javascript


【解决方案1】:

您必须使用 Date 创建 Date 对象才能使用它。

var d = new Date("1970-01-01 20:18:02");
document.write(d.getMinutes());

【讨论】:

  • 虽然这段代码 sn-p 可以解决问题,但它没有解释为什么或如何回答这个问题。请include an explanation for your code,因为这确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
【解决方案2】:

您可以执行以下操作:

var time = "00:20:40".split(":");
var minutes = time[1];

给定的字符串“00:20:40”不是有效的日期字符串,不能作为参数传递给 new Date()。在这种情况下,您可以使用上述解决方案,该解决方案将拆分字符串并为您提供一个由 [hh, mm, ss] 组成的数组,您将能够获得 time[1] 的分钟数。

希望对你有帮助。

【讨论】:

  • 我真的不建议在字符串的基础上使用日期/时间...
  • 你忘记了,如果它是一个 ISO 字符串,这可能会有很多问题。
  • @Weirdpanda,Jeff,根据他的问题,“00:20:40”不是标准日期字符串。它不能传递给 new Date()。我很想知道它是什么类型的数据以及他从哪里获取这些数据。
【解决方案3】:
function toSeconds (duration) {
  const regex = /(\d+):(\d+):(\d+)/;
  const matched = duration.match(regex);
  const hours = parseInt(matched[1]);
  const minutes = parseInt(matched[2]);
  const seconds = parseInt(matched[3]);
  return (hours * 60 * 60) + (minutes * 60) + seconds;
}

function toMinutes (duration) {
  const seconds = toSeconds(duration);
  return seconds / 60;
}

function toHours (duration) {
  const minutes = toMinutes(duration);
  return minutes / 60;
}

toSeconds('00:20:40') // 1240
toMinutes('00:20:40') // 20.666666666666668
toMinutes('01:20:40') // 80.66666666666667
toHours('01:20:40') // 1.3444444444444446

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    相关资源
    最近更新 更多