Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: IF time >= 9:30 then

Tags:

javascript

I'm trying to write a statement that says "if time is this and less than that then". I can use get hours and get min. However, I'm having problems combining a time such as 9:30.

Example,

var now = new Date();
var hour = now.getHours();
var day = now.getDay();
var mintues = now.getMinutes();

if (day == 0 && hour >= 9 && hour <= 11 && mintues >= 30) { 
    document.write(now); 
}

This only if the time is less between 9:30 10. As soon as the clock hits 10 the minutes are then < 30 and the script breaks.

Any thoughts on how to better incorporate the time function to make this theory work?

Thanks,

like image 377
Anthony James Avatar asked Dec 21 '10 21:12

Anthony James


People also ask

How to get current time in milliseconds JavaScript?

var currentTime = +new Date(); This gives you the current time in milliseconds.

How to use timestamp in JavaScript?

In JavaScript, in order to get the current timestamp, you can use Date. now() . It's important to note that Date. now() will return the number of milliseconds since January, 1 1970 UTC.

How to get time from timestamp in JavaScript?

If you instead want to get the current time stamp, you can create a new Date object and use the getTime() method. const currentDate = new Date(); const timestamp = currentDate. getTime(); In JavaScript, a time stamp is the number of milliseconds that have passed since January 1, 1970.

How to get time from date and time in JavaScript?

JavaScript Date getTime() getTime() returns the number of milliseconds since January 1, 1970 00:00:00.


1 Answers

use new Date().getTime() returns milliseconds for much easier comparison. This way there is no need to check hour, min, second, millisecond. Fiddle link

var d930 = new Date(2010, 12, 21, 9, 30, 0, 0), // today 9:30:00:000
    d931 = new Date(2010, 12, 21, 9, 31, 0, 0), // today 9:31:00:000
    t930 = d930.getTime(),
    t931 = d931.getTime();


console.log(t931 > t930);

This way your code can check against a static 9:30 time.

var time930 = new Date(2010, 12, 21, 9, 30, 0, 0).getTime(),
    sunday = 0,
    now = new Date();

if(now.getDay() == sunday && now.getTime() >= time930){
    /* do stuff */
}
like image 103
Josiah Ruddell Avatar answered Sep 30 '22 10:09

Josiah Ruddell