我有一個問題,我不確定如何使用 JS Date 物件計算調度日期和當前時間之間是否為一小時或更短。到目前為止,我所做的是將 entity.dispatchDate 字串轉換為 Date 物件,但是到目前為止,只要 todaysDate 日期物件等于或大于調度日期,我撰寫的這種情況就會回傳 true。我認為我首先要做的是,不要使用 1 小時,而是使用分鐘,因為我需要考慮該小時內的每個場景 - 例如,如果它是前一小時、15 分鐘或 30 分鐘回傳真的。到目前為止我所寫的:
// OPTIONS
const hoursBeforeSendout = 1;
// END OF OPTIONS
if(!entity.dispatchDate) {
return false;
}
var sendDate = new Date(Date.parse(entity.dispatchDate));
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() (h*60*60*1000));
return this;
}
var todaysDate = new Date();
todaysDate.addHours(hoursBeforeSendout);
if(todaysDate >= sendDate) {
return true;
}
return false;
我將不勝感激任何關于最佳方法的意見
uj5u.com熱心網友回復:
我建議簡單地從發送日期中減去當前日期(使用 Date.now())。
如果這低于閾值持續時間,則為“到期”或“關閉”:
function isDispatchDateClose(dispatchDate, thresholdMs = 3600 * 1000) {
if (!dispatchDate) {
return false;
}
const timeToDispatchDateMilliseconds = Date.parse(dispatchDate) - Date.now();
return (timeToDispatchDateMilliseconds <= thresholdMs);
}
let dispatchDates = [0, 30, 45, 90, 120].map(offsetMinutes => new Date(Date.now() offsetMinutes * 60000).toLocaleString('sv'));
console.log('Dispatch Date', '\t\t', 'Is Close ( < 1 hr to go)');
for(let dispatchDate of dispatchDates) {
console.log(dispatchDate, '\t', isDispatchDateClose(dispatchDate))
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
uj5u.com熱心網友回復:
如果您只想知道該dispatchDate值是否在(不到)1 小時內,那么有幾種方法可以很簡單地做到這一點。
最簡單的方法可能是(根據RobG的評論更新:
return new Date() - sendDate.getTime() >= 3600000;
根據您是否需要任何額外的靈活性,您還可以通過幾種不同的形式獲得剩余時間并決定從那里做什么:
// OPTIONS
const hoursBeforeSendout = 1;
// END OF OPTIONS
if(!entity.dispatchDate) {
return false;
}
var sendDate = new Date(Date.parse(entity.dispatchDate));
let _TimeRemaining = function(d) {
let timeRemaining = Math.floor((d.getTime() - new Date().getTime()) / 1000);
return {"hours": Math.floor(timeRemaining / 60 / 60), "minutes": Math.floor(timeRemaining / 60), "seconds": timeRemaining}
}
console.log(_TimeRemaining(sendDate)["hours"]); // returns the hours remaining
console.log(_TimeRemaining(sendDate)["minutes"]); // returns the minutes remaining
console.log(_TimeRemaining(sendDate)["seconds"]); // returns the seconds remaining
return _TimeRemaining(sendDate)["hours"] <= 0; // returns true if less than 1 hour
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/417192.html
標籤:
上一篇:用R創建日期
