Will this JS time code work? Can I make it better? - javascript

I'm displaying a message between Saturday at 6pm and Sunday 4am. The last time I had to do this it didn't work because I didn't take into account UTC time going negative when changing it to NYC time.
I am doing the math right (displaying at the appropriate times)?Should I put the UTC conversion code into its own function? Is this the worst js you've ever seen?
-- jquery is called --
$(document).ready(function() {
var dayTime = new Date();
var day = dayTime.getUTCDay();
var hour = dayTime.getUTCHours();
//alert(day.toString()+" "+hour.toString());
if (hour >= 5){
hour = hour-5;
}
else{
hour = hour+19;
if(day > 0){
day--;
}
else{
day = 6;
}
}
//alert(day.toString()+" "+hour.toString());
if ((day == 6 && hour >= 18) || (day == 0 && hour < 4)){
}
else{
$('#warning').hide(); //Want this message to show if js is disabled as well
}
});

Why do you even need that UTC stuff? Just work with local time:
var day = dayTime.getDay();
var hour = dayTime.getHours();
And you can clean up that conditional a bit too:
if (!(day == 6 && hour >= 18) && !(day == 0 && hour < 4)) {
$('#warning').hide();
}

This should get you your server's time:
var dayTime = new Date();
localOffset = dayTime.getTimezoneOffset() * 60000;
serverOffset = 5 * 60 * 60000;
dayTime = new Date(dayTime.getTime() + (localOffset - serverOffset));
Play around with that "5" in the server offset; it's the hours. It may need to be a -5; I'm not really sure.
Also, that's going to break every daylight savings. You'll have to detect that somehow and modify serverOffset.

Related

Can I use comparison and logical operators for time inputs in Javascript? [duplicate]

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,
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 */
}
You have a few typos and basic javascript errors.
Might wanna brush up on the basics.
W3Schools is where I learned all I know.
It works fine if you fix them...
var now = new Date();
var hour = now.getHours();
var day = now.getDay();
var minutes = now.getMinutes();
if(day == 0 && hour == 9 && minutes < 30 && minutes > 10 || day == 0 && hour == 9)
document.write('Time is between 9:10 and 9:30');
Think of the if statement as basic logic.
If the day is Sunday(0)
AND the hour is 9
AND the minutes are greater than 10
AND the minutes are less than 10
OR the day is Sunday(0)
AND the hour is before 9.
var now = new Date();
var closeTime = new Date();
closeTime.setHours(9); closeTime.setMinutes(30);
console.log(now, closeTime, now.getTime() >= closeTime.getTime());
close time is based on today, then we just change the hours and minutes to 9:30.
I made this solution simple and easy to read (thus easy to adjust).
// we need a function that makes hours and minutes a two digit number
Object.prototype.twoDigits = function () {
return ("0" + this).slice(-2);
}
// get current date and time
let now = new Date();
// compile the current hour and minutes in the format 09:35
timeOfDay = now.getHours().twoDigits() + ':' + now.getMinutes().twoDigits();
// test if timeOfDay is within a given time frame
if ('09:30' <= timeOfDay && timeOfDay <= '11:30') {
console.log('inside time frame');
} else {
console.log('outside time frame');
}
I had a similar problem to solve today, I setup a little component that returns if a place of business is open or not. Got the time by dividing the minutes by 100 then adding it to the hours. So 8:30 is represented as 8.3
let d = new Date()
let day = d.getDay()
let hours = d.getHours()
let minutes = d.getMinutes() / 100
let time = hours + minutes
if (day == 1) {
if (time > 8.3 && time < 17.3) {
setIsOpen(true)
} else {
setIsOpen(false)
}
}
if the hour is less than 9, true
or
if hour is 9 and minutes lt 30, true
so that would look like
if ((hour < 9) || (hour == 9 && minutes < 30))
Use words to figure out your logic. Symbols are just shortcuts.
One way is to do a direct comparison on date objects. Choose an arbitrary year, month and day, and then incorporate your times as follows:
var older = new Date("1980-01-01 12:15");
var newer = new Date("1980-01-01 12:30");
if (newer > older){
alert("Newer time is newer");
} else {
alert ("The time is not newer");
}
The MDC documentation on the Date object will help with some more details. The bottom line is that if you want to compare times, you don't actually need to call any methods on the objects, and it's possible to directly compare them. The date() object can take a variety of strings to assign a new time to the returned instance, these are from the MDC documentation:
today = new Date();
birthday = new Date("December 17, 1995 03:24:00");
birthday = new Date(1995,11,17);
birthday = new Date(1995,11,17,3,24,0);
As you can see, it's pretty simple. Don't complicate, and have a look through the documentation :)
While we're here, here's a test using your example:
var base = new Date("1980-01-01 9:30");
var test = new Date("1980-01-01 9:30:01");
if (test >= base){
alert("test time is newer or equal to base time");
} else {
alert ("test time is older than 9.30");
}
Try this:
var now = new Date();
var hour = now.getHours();
var mintues = now.getMinutes();
if(
(hour*60 + mintues) > 570 &&
hour <= 11
)
{
document.write(now);
}
I don't quite fully understand your question but hope this helps.
c = new Date();
nhour = c.getHours();
nmin = c.getMinutes();
if(nmin <= 9) {
nmin = "0" + nmin;
}
if(nhour <= 9) {
nhour = "0" + nhour;
}
newtime = nhour + "" + nmin;
if(newtime <= 0930){
alert("It is before 9:30am or earlier");
}

round carbon date to closest previous 6 hour mark

i have an application that executes a cron job every 6 hours:
00:00, 06:00, 12:00, 18:00
How do i round the current time to the lowest matching hour of the above?
So if its 13:05 now, it should return 12:00
edit: i meant in javascript, not in php. updated my question
You can use this function and it is without moment.js
function getRoundedTime(){
var d = new Date();
var now = d.getHours();
if(now > 6){
var roundedTime = now - (now % 6);
var stringTime = roundedTime.toString().concat(":00");
return stringTime;
}
if(now < 6){
return "00:00";
}
if(now % 6 === 0) {
return "0" + now.toString().concat(":00");
}
}
getRoundedTime();
Or if you want moment.js then import moment and inside function declare now like this var now = moment().hour();

Display div based on remote timezone and dates

I'm trying to display a chat div that displays between the hours of 8am-6pm Monday to Friday "Online" or show nothing if offline, based on the Eastern Time Zone (NYC), so that customers from Beijing will see Online or Offline based on these hours.
Simply need to show() or hide() the div. So far I have the hours, but I'm not sure how to get them to be in relation to the user time-zone.
$(document).ready(function () {
var start = new Date();
var end = new Date();
var time = new Date().getTime();
if (time > start.setHours(8,00) && time < end.setHours(18,00)) {
$('.online').show();
}
else {
$('.offline').hide();
}
});
The previous answer (seen in edit history) was to use the offset from UTC, however that isn't going to be an option if you want to support Daylight Savings; which is an important thing to do.
As such, the modification to the previous suggestion completely removes the use of UTC. To support daylight savings, the only proper way to get the time from EST is going to be to set the locale to that location, read the time, set up a new date object (which will technically be set up in the client local, but all we really want from it are the day and hour response from the Date object so we will ignore that technicality).
This is done by passing an object with the toLocaleString call which specifies the timezone, and then constructing a new date with the result of that.
var NYDate = new Date(new Date().toLocaleString("en-US", {timeZone: "America/New_York"}));
var NYHour = NYDate.getHours();
var NYDay = NYDate.getDay()
if (NYHour >= 8 && NYHour <= 18 &&
NYDay > 0 && NYDay < 6) {
$('.online').show();
}else {
$('.online').hide();
}
.online {
display: none;
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="online">Online</div>
No JavaScript needed. You should do this from the server side. (The customer doesn’t tell the store when it’s open, the store tells the customer!)
Assuming your HTML is being generated by some server-side language (PHP, Ruby, etc), set the program to use New York time, and simply calculate if you’re within the “open” times. If you’re open, generate the Chat div. if you’re closed... don’t.
(Or alternately, show/hide it via CSS and classes)
Turns out that this is not a completely trivial task using JavaScript (as noted in the answer from #StephenR, this may be easier to deal with server side). And as noted in some of the comments, using a library may be the better js approach.
That said, after thinking a bit about the comments from #RobG regarding varying browser support for options like timeZone in toLocaleString, I was curious what it would take to solve this another way (makes me grateful for the various js date libraries). Snippet below...
const getOffset = (month, date, day, hour) => {
// assume EST offset
let offset = 5;
// adjust to EST offset as needed
if ((month > 2 && month < 10) || (month === 2 && date > 14)) {
offset = 4;
} else if (month === 2 && date > 7 && date < 15) {
if ((day && date - day > 7) || (day === 0 && hour - offset >= 2)) {
offset = 4;
}
} else if (month === 10 && date < 8) {
if ((day && date - day < 0) || (day === 0 && hour - offset < 1)) {
offset = 4;
}
}
return offset;
};
const isOnline = () => {
const dt = new Date(); // current datetime
let year = dt.getUTCFullYear(); // utc year
let month = dt.getUTCMonth(); // utc month (jan is 0)
let date = dt.getUTCDate(); // utc date
let hour = dt.getUTCHours(); // utc hours (midnight is 0)
let day = dt.getUTCDay(); // utc weekday (sunday is 0)
let offset = getOffset(month, date, day, hour);
if (hour - offset < 0) {
hour = 24 + hour - offset;
day = day ? day - 1 : 6;
if (date === 1) {
if (!month) {
year -= 1;
month = 11;
} else {
month -= 1;
}
date = new Date(year, month + 1, 0).getDate();
} else {
date -= 1;
}
} else {
hour -= offset;
}
if (day > 0 && day < 6 && hour > 7 && hour < 19) {
return true;
}
return false;
};
if (isOnline()) {
console.log('online'); // handle online
} else {
console.log('offline'); // handle offline
}

Javascript Time Comparisons

I have two issues I need to solve using javascript or jQuery.
1) I need to test whether the current time falls between 7am and 7pm.
var now = new Date();
if (now >= *7am* && now < *7pm*){} else {}
2) On document load, I need a function to run everyday at 7am and 7pm.
Any help is appreciated.
Resolved part 2 by running a time check every 15 minutes.
var checkTime = setInterval(myFunction(), 900000);
You can use var currentHour = (new Date()).getHours(); to retrieve the specific hour as an integer between 0 and 23, according to the local timezone of your environment:
var currentHour = (new Date()).getHours();
if (currentHour >= 7 && currentHour < 19) { /* stuff */ } else { /* other stuff }
If you need to get UTC, there is the .getUTCHours() method.
The documentation has more information if you're interested: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours
Look at Date.getHours
$(function(){
var now = new Date();
var hours = now.getHours();
if (hours >= 7 && now < hours < 19){} else {}
});

Javascript strtotime formatting for non-specific dates

I need help with some Javascript strtotime-type code, please.
Our company runs a weekly promotion for 2 days only for its members. So when a member logs in, they see a banner promoting the promotion. If they happen to login outside of the promotion dates, the banner links to an information page. Otherwise, it links directly to the promotion.
Currently we're updating this by hand each week, which is a pain. We'd like to be able to use Javascript* to automatically change the link for us. OK, no problem, right?
Well, the thing is, what we don't want to have to do is go in and edit the script every week with the specific dates/times -- otherwise, what's the point? Currently the promotion runs Wednesday at 9a.m. to Thursday at 9a.m. It changes from time to time, every couple of months or so (Mon-Tue, 9a-9p, that sort of thing) so we will have to edit the script from time to time, but if we can avoid doing it weekly, that'd be great.
So here's what I came up with. It's heavily commented so my not-so-technical co-workers can go in and make the edits without too much difficulty.
var getData = function(){
var d = new Date();
var today = d.getDay(); // current day, numerically
var hr = d.getHours(); // current hour
// For Days:
// 0 = Sunday
// 1 = Monday
// 2 = Tuesday
// 3 = Wednesday
// 4 = Thursday
// 5 = Friday
// 6 = Saturday
var startDay = 3;
var endDay = 4;
// For Hours:
// This is a 24-hour clock. Midnight (12:00 AM) is 0, Noon = 12, 9 PM = 21, etc.
// So for a start time of 9 AM, put 9, and for an end time of 9 PM, put 21.
var startTime = 12;
var endTime = 15;
// Set the "url" variable to the NON-sale landing page. Put the SALE page URL in
// the "url" variables within the nested "if" statements below:
var url = 'http://link-to-the-non-promo-info-page';
if (( today >= startDay ) && ( hr >= startTime )) {
if ( today <= endDay ) && ( hr <= endTime )) {
url = 'http://link-to-the-live-promotion';
}
}
// ... non-essential variables and the actual display code
// below this line...
// ...
}
Notice I set the vars so that the promo runs 12p-3pm. If this were the real thing, the desired result would be for the promo link to display Wednesday 12pm to Thursday 3pm. What happens with this code, obviously, is that the promo banner is live Wednesday 12-3 and then Thursday 12-3.
I've goofed around with various permutations of the logic and haven't been able to hit the right one. Ultimately, I'd like to be able to open the script (or for one of my co-workers to open it), and be able to set the start day/time and end day/time, without having to set specific dates (Wednesday, July 24 to Thursday, July 25) and it just work.
If this were PHP I'd have it wrapped up. But it's Javascript, so any assistance I can get making this work would be fantastic.
Thanks,
Bob
UPDATE: #Kamala, I tweaked the time a bit by adding minutes, and a few other tweaks, but there's an issue of it not accepting the end time. Note that the script is set so that the start and end day is today, and the start/end times are now past (for EST zone, anyway) but the promo link is still being displayed:
var d = new Date();
var today = d.getDay(); // current day, numerically
var hr = d.getHours(); // current hour
var mn = d.getMinutes();
if (mn < 10) {
mn = "0"+mn;
}
var time = hr+":"+mn;
// For Days:
// 0 = Sunday
// 1 = Monday
// 2 = Tuesday
// 3 = Wednesday
// 4 = Thursday
// 5 = Friday
// 6 = Saturday
var startDay = 5;
var endDay = 5;
// For Hours:
// This is a 24-hour clock. Midnight (12:00 AM) is 0, Noon = 12, 9 PM = 21, etc.
// So for a start time of 9 AM, put 9, and for an end time of 9 PM, put 21.
var startTime = "11:00";
var endTime = "12:00";
// Set the "url" variable to the NON-sale landing page. Put the SALE page URL in
// the "url" variables within the nested "if" statements below:
var url1 = 'http://info-landing-page';
if (( today >= startDay ) && ( today <= endDay ) ) { // Awesome, we're within the promo days
if ( ( today != startDay && today != endDay ) // The promo is in full-swing - doesn't matter what time it is
|| ( today == startDay && time >= startTime )
|| ( today == endDay && time <= endTime ) ) {
url1 = 'http://promo-url';
alert("promo url set");
}
} else {
alert("we're pointing to the LP");
}
Is additional logic needed? Another nested "if" perhaps? I'm lost.
Thanks,
Bob
Try this...
if (( today >= startDay ) && ( today <= endDay ) ) { // Awesome, we're within the promo days
if( ( today != startDay && today != endDay ) // The promo is in full-swing - doesn't matter what time it is
||( today == startDay && hr >= startTime )
|| (today == endDay && hr <= endTime ) )
url = 'http://link-to-the-live-promotion';
}
}
So, what you need are two checks. If the promo's on day 1, is it after a certain time? Or if it's on day 2, is it before a certain time?
if ( today === startDay && hr >== startTime ) {
url = 'http://link-to-the-live-promotion';
} else if ( today === endDay && hr <== endTime ) {
url = 'http://link-to-the-live-promotion';
}
For your problem, there are no days in between the two days.. no need to check if day > startDay && day < endDay.
EDIT: Well, you probably want that capability in case your promo ever goes to 3 days. Here's another try handling this (rewritten to use OR's instead of if-else-if's:
if ((today > startDay && today < endDay) ||
(today == startDay && hr >= startTime) ||
(today == endDay && hr <= endTime)) {
url = 'http://link-to-the-live-promotion';
}

Categories