[英]constantly checking if time is 5:00 PM jquery
function updateTime() { var m_names = new Array("Jan", "Feb", "March", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"); var now = new Date(); var date = now.getDate(); var year = now.getFullYear(); var month = now.getMonth(); var currentHoursAP = now.getHours(); var currentHours = now.getHours(); var currentMinutes = now.getMinutes(); var currentSeconds = now.getSeconds(); // Pad the minutes and seconds with leading zeros, if required currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes; currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds; // Choose either "AM" or "PM" as appropriate var timeOfDay = (currentHours < 12) ? "AM" : "PM"; // Convert the hours component to 12-hour format if needed currentHoursAP = (currentHours > 12) ? currentHours - 12 : currentHours; // Convert an hours component of "0" to "12" currentHoursAP = (currentHoursAP == 0) ? 12 : currentHoursAP; // Compose the string for display //var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + " / " + currentHoursAP + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay; var currentTimeString = currentHoursAP + ":" + currentMinutes + " " + timeOfDay; //document.getElementById("TimeandDate").value = hour + ":" + minute + " " +"/" + " " + m_names[month] + " " + date + " " + year ; $('#TimeandDate').html("Time:" + currentTimeString + "<br>Date:" + m_names[month] + "/" + date + "/" + year); // $('#Time').text(currentTimeString); // $('#Date').text(m_names[month] + "/" + date + "/" + year); return currentTimeString; } updateTime(); setInterval(updateTime, 1000); // 5 * 1000 miliseconds console.log(updateTime()) if ((updateTime() == '5:00 PM')) { alert(updateTime()) }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <span id="TimeandDate"></span>
我想在我的項目中有一個時間檢查器。 我有一個功能,可以不斷更新時間跨度。 現在,我想繼續檢查跨度中的時間是否為5:00 PM
因為我需要顯示警報。 我試圖在函數中返回時間,例如
return currentTimeString
然后使用
if ((updateTime() == '5:00 PM')) {
alert(updateTime())
}
出於測試目的,我將if條件中的時間更改為最近的可能時間,但未顯示警報。
您的測試5:00 PM的代碼僅運行一次,您需要在updateTime()中進行測試以正確測試
例如
function updateTime() {
// ... code removed for clarity
var currentTimeString = currentHoursAP + ":" + currentMinutes + " " + timeOfDay;
// ... code removed for clarity
if ((currentTimeString == '5:00 PM')) {
alert("It's 5:00 PM")
}
}
updateTime();
setInterval(updateTime, 1000); // 5 * 1000 miliseconds
function isTriggerTime(hour, minute) { var now = new Date(); return (now.getHours() === hour) && (now.getMinutes() === minute); } setInterval(function() { if(isTriggerTime(17, 0)) { alert('it is time'); } }, 400);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.