I have an alert that will be triggered at exact 5:30 pm. I would like to make the date dynamic, I mean that it will get the system date. Because as you can see in my code, It only gets the time at the date I specify. Thanks!
function alert5pm() {
alert("It's already 5:30 pm and you only have 30 minutes left before to log-out");
}
var timeAt3pm = new Date("8/10/2012 05:30:00 PM").getTime()
, timeNow = new Date().getTime()
, offsetMillis = timeAt3pm - timeNow;
setTimeout('alert5pm()', offsetMillis);
For example:
Create an instance of the date to get the system date and time: var dateToday = new date();
from here, how can I extract an specific time. For example, I need to specifiy that I need to get the time 5:30pm at todays system date. Just like my code. But as you can see, It only gets the time at the date 8/10/2012. I want it to use the system date and time.
Any ideas?
Source: This SO Answer.
if you want to make the date configurable and set it from server side, I suggest you make an ajax call to server to fetch the time and date and set the value in javascript function
var time = ""
function alert5pm() {
alert("It's already 5:30 pm and you only have 30 minutes left before to log-out");
}
if( time == ""){
$.ajax({
type: "POST",
url: "some_server_url_to_fetch_data",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
time = msg.data;
var timeAt3pm = new Date(time).getTime();
var timeNow = new Date().getTime()
var offsetMillis = timeAt3pm - timeNow;
setTimeout('alert5pm()', offsetMillis);
}
});
}
else{
var timeAt3pm = new Date(time).getTime();
var timeNow = new Date().getTime()
var offsetMillis = timeAt3pm - timeNow;
setTimeout('alert5pm()', offsetMillis);
}
}
I think you need something like the code below:
function todayAt(hours,minutes)
{
var today = new Date();
today.setHours(hours);
today.setMinutes(minutes);
today.setSeconds(0);
return today;
}
alert(todayAt(17,30));
As a next step you can to improve the function and pass the parameters in any format you want (for example, in "5:30 AM" string.
So you will have the following code:
function alert5pm() {
alert("It's already 5:30 pm and you only have 30 minutes left before to log-out");
}
function todayAt(hours,minutes)
{
var today = new Date();
today.setHours(hours);
today.setMinutes(minutes);
today.setSeconds(0);
return today;
}
var targetTime= todayAt(17,30);
var offsetMillis = targetTime - Date.now();
setTimeout('alert5pm()', offsetMillis);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.