![](/img/trans.png)
[英]How to create a Set of user-defined objects in Javascript with a user-defined equality function?
[英]How to set user-defined time in Javascript and add 2 hours to it?
用戶以 12:00:00 的格式提供時間(以字符串形式),我想在時間上增加 1 或 3 小時並將其顯示為結束時間。
編碼:
function showCart(cart) {
for (var i = 0; i < cart.length; i++) {
var slotHtmlTr = '';
var c = i + 1;
slotHtmlTr += '<tr style="border: 1px solid black;" id="slot'+c+'">';
slotHtmlTr += '<td style="border: 1px solid black;">Slot '+c+'</td>';
slotHtmlTr += '<td style="border: 1px solid black;">'+cart[i].from_date+'</td>';
slotHtmlTr += '<td style="border: 1px solid black;">'+cart[i].start_time+'</td>';
slotHtmlTr += '<td style="border: 1px solid black;">End Time here</td>';
slotHtmlTr += '<td style="border: 1px solid black;">'+cart[i].room_id+'</td>';
slotHtmlTr += '<td style="border: 1px solid black;">'+cart[i].duration+'</td>';
var slotPrice = (cart[i].duration == "1") ? 15 : 30;
slotHtmlTr += '<td style="border: 1px solid black;">'+slotPrice+ '</td>';
slotHtmlTr += '</tr>';
}
$('#slotsDetails').append(slotHtmlTr);
// console.log(slotHtml);
}
我如何添加時間:
let hrsAdd = 3;
let start_time = cart[i].start_time;
let end_time = new Date(start_time); //showing some error
console.log(end_time + hrsAdd);
我知道我做錯了什么,但不知道是什么?
提前致謝!
您必須記住 Date class 對創建它有一些限制,因此您不能只在構造函數上設置時間,它必須采用特定的格式。 有關更多詳細信息,請查看 JS 日期 class 文檔。
您可以使用與此類似的代碼來計算時間:
srcTime = "12:01:02"; // value sent by the user
baseDateTime = new Date(); // the date does not matter to us, but it comes together as it is the Date class
[srcHour, srcMinute, srcSecond] = srcTime.split(":"); // we separate the value in the right variables
baseDateTime.setHours(parseInt(srcHour) + 3); // update the Date object with user hour + 3 hours
// from this point on you can work with the baseDateTime variable to extract the time, date and etc.
// for example:
end_time = baseDateTime.getHours() + ":" + baseDateTime.getMinutes() + ":" + baseDateTime.getSeconds();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.