Javascript strtotime formatting for non-specific dates - javascript

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';
}

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");
}

JS Check for holidays

I have call center and I use this JS code to let messages come in during business hours and after business hours/weekends it display a message saying that is outside of support time, my question is, how I make this code work also for holidays?
exports.handler = async function(context, event, callback) {
const moment = require('moment-timezone');
var now = moment().tz('America/New_York');
console.log('Current time-->'+now);
console.log('current hours-->'+now.hour());
let isWorkingHours = false;
//let isWorkingHours = true; // testing
const weekday = now.isoWeekday();
console.log('weekday-->'+weekday);
if (now.hour() >= 9 && now.hour() <= 17 && weekday <= 5) {
//if (now.hour() >= 4 && now.hour() <= 20 && weekday <= 2) { // testing
isWorkingHours = true;
//Console.log('This is outside working hours');
}
callback(null, {
isWorkingHours: isWorkingHours
});
}
I got this holiday checker from someone else's post here on StackOverflow (I should have documented the link, but I forgot to). You can iterate through all the dates you are interested in to create a complete list of holidays, or just check if a given date is a holiday
function check_holiday (dt_date) {
// check simple dates (month/date - no leading zeroes)
var n_date = dt_date.getDate(),
n_month = dt_date.getMonth() + 1;
var s_date1 = n_month + '/' + n_date;
if ( s_date1 == '1/1' // New Year's Day
|| s_date1 == '6/14' // Flag Day
|| s_date1 == '7/4' // Independence Day
|| s_date1 == '11/11' // Veterans Day
|| s_date1 == '12/25' // Christmas Day
) return true;
// weekday from beginning of the month (month/num/day)
var n_wday = dt_date.getDay(),
n_wnum = Math.floor((n_date - 1) / 7) + 1;
var s_date2 = n_month + '/' + n_wnum + '/' + n_wday;
if ( s_date2 == '1/3/1' // Birthday of Martin Luther King, third Monday in January
|| s_date2 == '2/3/1' // Washington's Birthday, third Monday in February
|| s_date2 == '5/3/6' // Armed Forces Day, third Saturday in May
|| s_date2 == '9/1/1' // Labor Day, first Monday in September
|| s_date2 == '10/2/1' // Columbus Day, second Monday in October
|| s_date2 == '11/4/4' // Thanksgiving Day, fourth Thursday in November
) return true;
// weekday number from end of the month (month/num/day)
var dt_temp = new Date (dt_date);
dt_temp.setDate(1);
dt_temp.setMonth(dt_temp.getMonth() + 1);
dt_temp.setDate(dt_temp.getDate() - 1);
n_wnum = Math.floor((dt_temp.getDate() - n_date - 1) / 7) + 1;
var s_date3 = n_month + '/' + n_wnum + '/' + n_wday;
if ( s_date3 == '5/1/1' // Memorial Day, last Monday in May
) return true;
// misc complex dates
if (s_date1 == '1/20' && (((dt_date.getFullYear() - 1937) % 4) == 0)
// Inauguration Day, January 20th every four years, starting in 1937.
) return true;
if (n_month == 11 && n_date >= 2 && n_date < 9 && n_wday == 2
// Election Day, Tuesday on or after November 2.
) return true;
return false;
}
The logic for checking if an specific instant in time is outside working ours is in your if statement.
I would abstract this in some sort of storage, based on time ranges for holidays or any day off. You could either have a table or cache where to store these holidays (you should load them in advance).
That way, you can do something like:
Search if there's a holiday whose date matches with the current date (matching just date without timestamp, you can use moment's isSame checking just by date)
If there's a match, return isWorkingHours as false
To check if the date matches, you can use this (regardless of current time, it returns true as you're comparing at date level):
console.log(moment('2021-05-10 14:00:00').isSame('2021-05-10', 'day'));
Here's a list of things that you might want to check for:
Weekends
"Static date" holidays (eg: Christmas)
"Variable date" holidays (eg: Easter)
Times (eg: your office opens at 8:00)
/* Function that checks if office is available at a specific date
* #returns {boolean}
*/
function is_office_available (date = new Date()) {
// weekends, or actually any other day of the week
let day = date.getDay();
if ( [0 /*sunday*/, 6 /*saturday*/].includes(day) ) return false;
// "static date" holidays (formatted as 'DD/MM')
let dd_mm = date.getDate() + '/' + (date.getMonth()+1);
if ( ['24/12', '25/12'].includes(dd_mm) ) return false;
// TODO: "variable date" holidays
// specific times
// this logic has to be extended a LOT if, for example, you have
// the office open from 8:30 to 17:30 with a launch break from 12:00 to 13:00 on weekdays
// and from 9:00 to 12:00 only on mondays
let hh = date.getHours();
if (9 < hh || hh > 17) return false;
// if no test returned true then the office is going to be available on that date
return true;
}
You can simply call this function in an if statement.
"Variable date" holidays have a quite a long (and boring) implementation to do and it depends on the ones you have in your country office.

How to make timeago.js show only hours ago

I am using timeago.js to show the date. However, I want to show the "hours ago" feature of the plugin if a particular date is less than 2 days. If a date is more than 2 days, it'll show the usual "3 days ago".
Thanks for the help in advance.
Apparently, I have to modify the plugin. Have to set the "hours" to be less than 48 hours.
var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
hours < 48 && substitute($l.hours, Math.round(hours)) ||
You can of course modify plugin like you did, or you could run the dates over again and check whether they are more than two days or not - if they are - just rewrite the string to hours, something like this:
$(function(){
var oneHour = 1*60*60*1000; // one hour in miliseconds
var twoDays = 2*24*oneHour; // two days in miliseconds
$('.timeAgoSelector').each(function(){
$t = $(this);
var agoDate = new Date( $t.attr('title') ).getTime()
var currDate = new Date().getTime();
var timeAgo = currDate - agoDate;
if( (timeAgo < twoDays) && (timeAgo >= oneHour) ){
var hours = ((timeAgo/1000)/60)/60;
hours = Math.floor(hours);
if( hours < 2 ) $t.html( 'an hour ago' );
else $t.html( hours + ' hours ago' );
} //else => do nothing (keep original content)
});
});
=> http://jsfiddle.net/chgvcudL/
I think timeago.js can help you, and the tiny library is supported by me.
You can just customize you locale function for your need.
const yourLocale = (number, index, totalSec) => {
// format totalSec into hours.
const hours = getHours(totalSec);
return hours +' hours ago';
};
Then register it.
timeago.register('yourLocale', yourLocale);
Them format use it.
timeago.format(time, 'yourLocale');
done!

how to check a date is within current week or current month or next month in javascript?

I have some friends' birthdays and want to separate them as follows :
birthdays which fall within the current week (within remaining days of current week starting from current day).
birthdays which fall within the current month (within remaining days of current month starting from current day).
birthdays which fall within the next month.
So all I want to know how to test each date in javascript to see if it falls within the remaining days of the current week/current month/next month.
N.B: say I have those dates in m/d/Y(06/29/1990) format.
Thanks
Convert your date and current time to Date object and use it for comparison. Some dry coding:
var now = new Date()
if (
(check.getFullYear() == now.getFullYear()) &&
(check.getMonth() == now.getMonth()) &&
(check.getDate() >= now.getDate())
) {
// remanining days in current month and today. Use > if you don't need today.
}
var nextMonth = now.getMonth() + 1
var nextYear = now.getFullYear()
if (nextMonth == 12) {
nextMonth = 0
nextYear++
}
if (
(check.getFullYear() == nextYear) &&
(check.getMonth() == nextMonth)
) {
// any day in next month. Doesn't include current month remaining days.
}
var now = new Date()
now.setHours(12)
now.setMinutes(0)
now.setSeconds(0)
now.setMilliseconds(0)
var end_of_week = new Date(now.getTime() + (6 - now.getDay()) * 24*60*60*1000 )
end_of_week.setHours(23)
end_of_week.setMinutes(59)
end_of_week.setSeconds(59) // gee, bye-bye leap second
if ( check >=now && check <= end_of_week) {
// between now and end of week
}
the code Using the Parse Date is
var selecteddate = '07/29/1990';
var datestr = selecteddate.split('/');
var month = datestr[0];
var day = datestr[1];
var year = datestr[2];
var currentdate = new Date();
var cur_month = currentdate.getMonth() + 1;
var cur_day =currentdate.getDate();
var cur_year =currentdate.getFullYear();
if(cur_month==month && day >= cur_day)
{
alert("in this month");
}
else
{
alert("not in this month");
} ​

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

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.

Categories