我從一個外部的JSON中得到這個時間 :
"time": "19:45"
我需要從這個字串中添加2個小時。
這在JS中可能嗎?
謝謝
uj5u.com熱心網友回復:
試試這個
。let myTime = '19:45'
function getTime(time, addHour) {
let [h, m] = time.split(': ')。
let date = new Date();
date.setHours(h, m, 0)
date.toString()。
let res = `${date.getHours() addHour}: ${date.getMinutes()}`
return res
}
console.log(getTime( myTime, 2 ) )
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
使用String.split獲得hourNum和minuteNum,然后構造一個Date物件,使用setTime增加兩個小時。
function addHours(text, hours=2) {
const [hourNum, minNum] = text.split(': ')
const time = new Date(0, 0, 0, hourNum, minNum)
time.setTime(time.getTime() (hours * 60 * 60 * 1000)
return `${time.getHours()}:${time.getMinutes()}`
}
console.log(addHours('19:45',2)
console.log(addHours('23:45', 2))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
一個Date物件并不是做時間數學的必要條件,它只是意味著要考慮到分和秒(60),也許還有天(24)。
例如:
。
//將時間添加到一個時間戳中,均為HH:mm格式。
//如果 respectDay 為真,小時數為 % 24。
function addTime(start, increment, respectDay = false) {
let pad = n => ('0' n).slice(-2)。
let timeToMins = time => time.split(': ')。 reduce((h, m) => h*60 m*1) 。
let minsToTime = (mins, respectDay = false) => `${pad((mins / 60 | 0) % (尊重日? 24 : Number.POSITIVE_INFINITY))}:${pad(mins%60)}`;
return minsToTime(timeToMins(start) timeToMins(increment), respectDay) 。
}
let time = "19:45"/span>;
console. log(addTime(time, '8:23')); //總時間 : 28:08。
console。 log(addTime(time, '8: 23', true)); // As day time : 04:08
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/312008.html
標籤:
上一篇:JWT應該保存在哪里?
下一篇:格式字串漏洞之任意地址覆寫大數字
