JS: Convert duration string to millisecond kiểu như Jira Atlassian
Code convert duration string to millisecond kiểu như Jira Atlassian sẽ thế nào?
duration
Remain: 5
1 Answer
monkey
Enlightened
monkey
Enlightened
Code:
<span>var</span> simpleDurationStringToMillis = <span><span>function</span>(<span>str</span>) </span>{ <span>if</span> (!str) { <span>return</span> <span>0</span>; } <span>var</span> answer = <span>0</span>; <span>var</span> millisBySymbol = { <span>'ms'</span>: <span>1</span>, <span>'s'</span>: <span>1000</span>, <span>'m'</span>: <span>60</span> * <span>1000</span>, <span>'h'</span>: <span>60</span> * <span>60</span> * <span>1000</span>, <span>'d'</span>: <span>24</span> * <span>60</span> * <span>60</span> * <span>1000</span>, <span>'w'</span>: <span>7</span> * <span>24</span> * <span>60</span> * <span>60</span> * <span>1000</span>, <span>'M'</span>: <span>30</span> * <span>24</span> * <span>60</span> * <span>60</span> * <span>1000</span>, <span>'y'</span>: <span>365</span> * <span>24</span> * <span>60</span> * <span>60</span> * <span>1000</span> }; <span>var</span> <span>number</span> = <span>''</span>; <span>for</span> (<span>var</span> i = <span>0</span>; i < str.length; ++i) { <span>if</span> (i >= <span>'0'</span> && str[i] <= <span>'9'</span>) { <span>number</span> += str[i]; } <span>else</span> { <span>var</span> symbol = str[i]; <span>if</span> ((i + <span>1</span>) < str.length) { <span>if</span>(str[i + <span>1</span>] >= <span>'1'</span> && str[i + <span>1</span>] <= <span>'9'</span>) { symbol += str[i + <span>1</span>]; ++i; } } <span>var</span> millis = millisBySymbol[symbol]; <span>if</span> (millis && <span>number</span>) { answer += <span>parseInt</span>(<span>number</span>, <span>10</span>) * millis; <span>number</span> = <span>''</span>; } <span>else</span> { answer = <span>-1</span>; <span>break</span>; } } } <span>return</span> answer; }
Ví dụ:
console.log(simpleDurationStringToMillis('0')); console.log(simpleDurationStringToMillis('1ms')); console.log(simpleDurationStringToMillis('10s')); console.log(simpleDurationStringToMillis('100m')); console.log(simpleDurationStringToMillis('1000h')); console.log(simpleDurationStringToMillis('10000d')); console.log(simpleDurationStringToMillis('1000000w')); console.log(simpleDurationStringToMillis('10000000M')); console.log(simpleDurationStringToMillis('100000000y')); console.log(simpleDurationStringToMillis('a')); console.log(simpleDurationStringToMillis('12a')); console.log(simpleDurationStringToMillis('3mss'));
Kết quả:
0 1 10000 6000000 3600000000 864000000000 604800000000000 25920000000000000 3153600000000000000 -1 -1 -1
-
0