0

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.

Community
  • 1
  • 1
Luke Villanueva
  • 2,030
  • 8
  • 44
  • 94

2 Answers2

0

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);
}
}
Anand
  • 14,545
  • 8
  • 32
  • 44
0

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); 
Mikhail Payson
  • 923
  • 8
  • 12
  • Can you help me incorporate your code with my existing code? I didn't quite understood on how I will use your code blocks. Thanks! – Luke Villanueva Aug 12 '12 at 19:17