javascript - Google API 转换持续时间 [英] javascript - Google API converting duration
问题描述
目前我正在使用谷歌 API 来计算距离和持续时间,这在字符串中非常有效,但是我不想将此数据存储为:
Currently I am using a google API to calculate distance and duration, and this works brilliantly into a string, however i don't want to store this data as:
2 hours 10 mins
有没有一种简单的方法可以在几分钟内转换这种格式?(130)
我的逻辑是从字符串中提取数字,使值等于 210,然后对此进行一些数学计算:
my logic would be extract the numbers from the string so the value equals 210, and then perform some mathematical calculation on this:
var dur = screen.LabourAllocation.Duration;
var dura = dur.match(/\d/g);
dura = dura.join("");
还有其他人可以提出比这更好的方法吗?如果不是,我可以做什么计算将 210 转换为分钟 (130)?
can anyone else suggest a better method than this? if not what calculation could i do to convert 210 to minutes (130)?
感谢您的帮助
推荐答案
你必须得到所有的数字部分,你的正则表达式只能一个一个地捕捉数字,所以你需要 /\d+/g
,然后简单的数学.
You have to get all number parts, your regex only catch numbers one by one so you need /\d+/g
, then simple math.
var dur = "2 hours 10 mins";
var dura = dur.match(/\d+/g); // take all "grouped" number
// dura ["2", "10"]
dura = dura[0] * 60 + (+dura[1]);
// first one is hours , second one need to be converted to number
这篇关于javascript - Google API 转换持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!