Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

javascript - 如何将“ 1h30m”样式的持续时间解析为Moment.js持续时间(How to parse “1h30m” style durations into a Moment.js duration)

I would like to try and convert time duration strings to a moment.js duration object.

(我想尝试将持续时间字符串转换为moment.js持续时间对象。)

An example of the string format is as follows: "1h30m", which should correspond to 1 hour, 30 minutes, and 0 seconds.

(字符串格式的示例如下:“ 1h30m”,应对应于1小时30分钟0秒。)

My first thought was to use regex so that I could pull the hours, minutes and seconds but I have a feeling that there's a more efficient way to handle it - the end goal is to use these to calculate how long until a command is run - I saw there was a library called momentjs that I feel could possibly handle this, but the docs don't give a clear way on handling duration formatting in the format that I have in mind.

(我的第一个想法是使用正则表达式,以便我可以拉动小时,分钟和秒,但是我感觉有一种更有效的处理方式-最终目标是使用这些来计算直到运行命令多长时间-我看到有一个名为momentjs的库,我觉得可能可以解决这个问题,但是文档并没有提供一种清晰的方式来处理我所想到的格式的持续时间格式。)

I can provide the code I have written so far, though I don't imagine it would be of much help.

(我可以提供到目前为止已经编写的代码,尽管我认为这不会有太大帮助。)

  ask by secondubly translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, you can use moment.js to do this - but I'm not sure if it's strictly necessary as it can also be accomplished through simple string manipulation.

(是的,您可以使用moment.js来执行此操作-但我不确定它是否严格必要,因为它也可以通过简单的字符串操作来实现。)

String Manipulation Approach:

(字符串处理方法:)

function parseTimeSpan(timeString) {
  let parts = timeString.split("h");
  return {
    hours: Number(parts[0]), 
    minutes: Number(parts[1].slice(0, -1))
  };
}

JsFiddle Here

(JsFiddle在这里)

Note this will only work with strings that contain both the hour and minute component, and does not support seconds.

(请注意,这仅适用于同时包含小时和分钟部分且不支持秒的字符串。)

Moment.JS Approach:

(Moment.JS方法:)

function parseTimeSpan(timeString) {
  return moment.duration("PT" + timeString.toUpperCase());
}

JsFiddle Here

(JsFiddle在这里)

This approach is more robust and handles far more use cases, but is slower and requires an external library.

(这种方法更健壮,可处理更多用例,但速度较慢,需要外部库。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...