I'm currently trying to create a JavaScript which will display on our website when our shop is open, and when it is closed.
I basically want to create an if statement between two times, these being 8:30 and 5:30.
I'm currently doing the following, although it won't work as I effectively have two lots of 'minutes' defined which cancel each other out.
<script type="text/javascript">
var Digital=new Date();
var day=Digital.getDay();
var hours=Digital.getHours();
var minutes=Digital.getMinutes();
// Monday - Open //
if (day==1 && hours>=8 && minutes>=30 && day==1 && hours<=17 && minutes<=30)
document.write('Open today until 5:30pm');
</script>
Can anyone suggest a way of achieving what I am trying to do?
How about this:
if(day == 1 && hours*60+minutes >= 510 && hours*60+minutes <= 1050) {
// do stuff
}
With 8 * 60 + 30 = 510 and 17 * 60 + 30 = 1050.
One thing to note here is
new Date()
gets the local time from the client's clock. If the client's clock is set at a different time zone you might not get the result you are hoping for.
I would suggest getting the client's timezone as well and converting that to your desired timezone adding/subtracting any offset, start with something like
var clientTime = new Date();
var clientTimeZone = clientTime.getTimezoneOffset();
//getTimezoneOffset returns the time-zone offset in minutes between the current locale and UTC.
Related
Hi first time posting here so bear with me.
I've got a live stream that I want to show on Sundays between 6am and 2pm (CEST - Central European Summer Time)
I've got the first part down but how do I make it timezone specific? Make sense?
$(document).ready(function() {
var d = new Date();
var n = d.getDay();
var hour = d.getHours();
if(n == 0 && hour >= 6 && hour < 14)
{
$(".stream").show();
} else {
$(".stream").hide();
}
} );
PS I understand this doesn't hide it completely outside of those times and that's fine. I'm just looking for a solution that works on the client side.
I've been developing a web application Dashboard and I was wondering how to detect that is midnight in order to reset some arrays that contains datas from the previous day using jquery or momentjs.
Use moment().format("h:mm:ss") that returns time in a h:mm:ss format.
var midnight = "0:00:00";
var now = null;
setInterval(function () {
now = moment().format("H:mm:ss");
if (now === midnight) {
alert("Hi");
}
$("#time").text(now);
}, 1000);
JSFIDDLE
A better way would be to compute the seconds until midnight. This is very simple and human readable using MomentJS:
// returns the number of seconds until next midnight
moment("24:00:00", "hh:mm:ss").diff(moment(), 'seconds');
So, just do:
setTimeout(
midnightTask,
moment("24:00:00", "hh:mm:ss").diff(moment(), 'seconds')
);
function midnightTask() {
/* do something */
}
JSFIDDLE
There's only really two ways to accomplish this
poll every x seconds and see whether we're within x seconds of midnight
Calculate the time between now and midnight, and sleep for that amount of time before executing
(1) has been demonstrated in other answers, here's (2).
The first thing to do is calculate the number of milliseconds until midnight then use that as a parameter to javascripts setTimeout.
setTimeout(function(){
// whatever you want to do at midnight
}, msToMidnight);
After you've finished your work in that function, you might want to recaculate the time until next midnight and repeat the process.
So I think you're going about this the wrong way. What you're looking for isn't when it's midnight, you just want to know when the day has changed, which is a much simpler task.
The first thing I'm going to say is avoid using timers at all costs. They're not worth it. The performance hit and extra CPU time you take from running the same function >3600 times a day is ridiculous, especially when it's running on someone else's computer. You don't know how much it can handle, so assume it can't handle much at all. Go easy on your users.
I would suggest listening to a user input event, assuming that this is something you would have on a regular computer, and not something like this, where there is no user input.
If user input events are something you could rely on, I would do this..
var today = new Date(), lastUpdate;
window.addEventListener( "mousemove", function () {
var time = new Date();
// If we haven't checked yet, or if it's been more than 30 seconds since the last check
if ( !lastUpdate || ( time.getTime() - lastUpdate.getTime() ) > 30000 ) {
// Set the last time we checked, and then check if the date has changed.
lastUpdate = time
if ( time.getDate() !== today.getDate() ) {
// If the date has changed, set the date to the new date, and refresh stuff.
today = time
this_is_where_you_would_reset_stuff()
}
}
} )
If you absolutely need to use a timer, then I would do this..
function init() {
var today = new Date();
var midnight = new Date();
midnight.setDate( today.getDate() + 1 )
midnight.setHours( 0 )
midnight.setMinutes( 0 )
setTimeout( function () {
// If the date has changed, set the date to the new date, and refresh stuff.
today = time
this_is_where_you_would_reset_stuff()
init()
}, midnight.getTime() - today.getTime() )
}
init()
Keep in mind that the second way is likely to be far less reliable.
Create a date at midnight this morning, add 86400 seconds, and set a timeout for then:
new Date(Date.parse((new Date()).toString().replace(/\d\d:\d\d:\d\d/,'00:00:00')) + 86400 * 1000)
Here's how you'd use it:
var delay_to_midnight = Date.parse((new Date()).toString().replace(/\d\d:\d\d:\d\d/,'00:00:00')) + 86400 * 1000 - Date.now()
var timeoutid = window.setTimeout(function() { alert("It's midnight!"); }, delay_to_midnight);
I would try:
window.setInterval(resetAtMidnight, 1000*5) // every five seconds
function resetAtMidnight() {
var now = new Date();
if(now.getHours() < 1
&& now.getMinutes() < 1
&& now.getSeconds() < 5 ) {
redrawPage();
}
};
We have a system script that runs everyday at 1 AM PST. We have users around the world. We want to provide a simple web page that uses JavaScript to show 1 AM PST in the user's local timezone. For instance, a user in New York City should see 4 AM PST as the time the system script will run.
The PST time format is HH:MM DD.YYYY.
This only needs to work on mobile Safari.
What's the best way to do this?
The code would something like this:
alert(new Date(your_pst_server_time).toLocaleString());
You can use the .getUTCHours() and .getTimezoneOffset() methods of the new Date() object. For the ease of use, I attached this new function to that object. It will accept a parameter that specifies the time format that gets returned.
Date.prototype.getLocalTime = function (format){
var date = new Date();
var finalTime = ((date.getUTCHours()-2))-(((date.getTimezoneOffset())/60));
if (format+'' != '24'){
if (finalTime < 0){ finalTime = finalTime + 24 }
}
else {
if (finalTime > 12){ finalTime = (finalTime - 12)+" PM" }
else { finalTime += " AM" }
}
return finalTime.toString();
}
With my CET timezone, calling new Date().getLocalTime('24') will return "10" and calling new Date().getLocalTime() (without parameters or a parameter that isn't "24") will return "10 AM".
Time Conversion Site to check timezones
This function is a reasonable first start, but would not cope with countries like India which have a time offset of x.5 hours (x hours + 30mins). Unfortunately you cannot just divide by 60 like that.
I have created a small function that i need on my site successfully in php. But i now realise i actually need this in javascript or jquery as PHP will only excute this code on load.. i need this function to work with onchange on a select. The code below is my function.. Can anyone point out where i start to convert this into js/jquery like code:
function setTrnTime ($hr, $journeyTime){
date_default_timezone_set('GMT');
//convert current hour to time format hour
$currentHour = (date("H", mktime($hr)));
// Journey time in hours
$journey = $journeyTime
$journey = $journey/60; // Get hours
$journey = ceil($journey); // Round off to next hour i.e. 3 hours 20mins is now 4 hours
// New Hours
$NewHour = (date("H", mktime($journey)));
$Newhour = $NewHour*60*60; // convert to seconds
// Final hour is Current Hour - JourneyTime (Hours)
$trnHour = (date('H', mktime($currentHour-$NewHour)));
return $trnHour;
}
With the code above, if i pass two values 06, 60: that would mean my answer would be 05. e.g. 06 is 6am. 60 is 60mins.. so 6am - 60mins = 5am.
You can do the same in javascript using the Date object, see info here
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
EDITED: Added some code, also not even using the Date object.
But do you need something that complex, doesn't the following do what you are after with less steps.
http://jsfiddle.net/WWTDc/
If hr is a Date object, then it's very simple. Otherwise you can create a Date object and set its hour:
//! \param[in] hr Date object or hour (0--23)
//! \param[in] journeyTime journey time in minutes.
function setTrnTime(hr,journeyTime){
var end;
if(typeof(hr) === 'number'){
end = new Date();
end.setHours(hr);
}
else
end = hr;
return (new Date(end - journeyTime*60*1000)).getHours();
}
This will return the hour (demonstration).
See here for information about Date object in JavaScript.
im trying to write a little .js file to change a css style from display:block to display:none depending on the time of day, 08.30 to 17.00 display block and 17.00 to 08.30 display none.
Here's what i have so far:
<script language="JavaScript">
day=new Date() //..get the date
x=day.getHours() //..get the hour
if(x>=8.30 && x<17) {
document.write('<style type="text/css">#live{display:block}"></style>')
} else
if(x>=17 && x<8.30) {
document.write('<style type="text/css">#live{display:none}"></style>')
};
</script>
Do think this is good js plus not sure if using 8.30 would work plus not sure if the last ";" is needed.
Any help on this would be great thanks.
Im now trying this code but does not work
<script type="text/javascript">
$(document).ready ( function (){
var dateObj = new Date();
var hour = dateObj.getHours() * 100 + dateObj.getMinutes();
if (hour >= 1600 && hour <= 1800) {
document.getElementById('live').style.display = "none";
}
});
</script>
Date().getHours() returns an integer. For your code to work you'd have to do something like this:
var dateObj = new Date();
var hour = dateObj.getHours() * 100 + dateObj.getMinutes();
if (hour >= 830 && hour <= 1700) {
document.getElementById('your_el').style.display = "none";
}
Note that you should only use this code when the DOM is ready for manipulation.
Although, is this really what you want? JavaScript's Date gets its date and time information from the users' clock. You would probably be better off handling this on the server.
getHours() returns a whole number (0 to 23). For 8:30, you will
need to check getHours() and getMinutes() accordingly.
The last semicolon does not need to be there.
getHours() only gets you the hours number, you need to get the minutes as well
try with
x=day.getHours()+ (day.getMinutes()/100);
about the ; it is not neccessary after an if, but it's good practice to put it at the end of each code line (that would be every other line)