comparing two time values in an if statement - javascript

i need to compare two values and do stuff with the result of the comaprison depending on if the times are more than 1 hour apart.
So for example
Time1 = 13:07:01
Now = 13:26:47
what i need to do is in an if statement compare to see if Now is an hour ahead of Time one for example
If( Comparison){
1 hour has passed
}else{
1 hour has not passes
}
What would be the best way to do this?

Use Date() - MDN
if (Date.now() > new Date(oldDate) + 1000 * 60 * 60) {
console.log('1 hour has passed');
} else {
console.log('1 hour has not passed');
}

<script>
function checkForOneHr(){
var start = '5:30';
var end = '6:50';
s = start.split(':');
e = end.split(':');
min = e[1]-s[1];
hour_carry = 0;
if(min < 0){
min += 60;
hour_carry += 1;
}
hour = e[0]-s[0]-hour_carry;
if(hour >= 1)
return true;
else
return false;
}
if( checkForOneHr()){
alert('1 hour has passed');
}else{
alert(' hour has not passes ');
}
</script>

If they are Date objects
var now = new Date();
var diff = now.getTime() - time1.getTime();
if(diff >= 1000*60*60) {
console.log('an hour has passed');
} else {
console.log('an hour has not passed');
}

First of All , Convert Both the times to string format using,
strtotime().
See any PHP manual.
Take out the difference of them.
The result will be difference in seconds.
Divide the difference by 3600.
If it is greater then 1, do your 'Code to do".
eg.
$current_time = date('T-m-d H:I:S');
$time_now = strtotime($current_time);

Related

Javascript: How Do I Refresh Page At Midnight?

I have been trying to get my page to refresh at midnight, but the code I wrote is not working.
This is the code that I have written:
function reloadClock() {
var reloadTime = new Date();
var hrs = reloadTime.getHours();
var min = reloadTime.getMinutes();
var sec = reloadTime.getSeconds();
// I tried this code, it will not work.
if (hrs == 0 && min == 0 && sec == 0) {
alert('this page will now reload');
location.reload();
}
// I also tried this code, still can't get it to work.
if (hrs == 14) { // Works as intended.
alert(hrs);
if (min == 31) { // Works as intended.
alert(min);
if (sec == 0) { // Does not work as intended.
alert(sec);
location.reload();
}
}
}
setTimeout(reloadClock(), 1000);
}
Does anyone know a solution for this?
check this
const timerefresh = setInterval(function(){
const time_ = new Date().toLocaleString('en-GB'); // return 24 hour time format in string, explaination about en-GB you can search on wikipedia, thats bored (:
let date = time_.split(', ')[0].split('/'); // split the time strings to get date in array [day, month, year]
let clock = time_.split(', ')[1].split(':'); // split the time strings to get clock in array [hour, min, sec]
countDownTime(Number(clock[0]),Number(clock[1]),Number(clock[2]));
document.getElementById('time1').innerHTML = 'date:'+date+', clock:'+clock;
},1000);
function countDownTime(h,m,s){
// some match to reverse the clock
document.getElementById('time2').innerHTML = 'countdown to midnight : '+ (23-h)+':'+(59-m)+':'+(60-s);
if(h === 23 && m === 59 && s === 59){ itsMidnight(); } // call its midnight 1 sec before clock 00:00:00
}
function itsMidnight(){
// its midnight, your function here
console.log('midnight! reload.')
window.location.reload();
}
// code below just for testing, you can delete it
let sectomidnight = 50;
function gotoMidnight(){
clearInterval(timerefresh);
setInterval(function(){
sectomidnight += 1;
countDownTime(23,59,sectomidnight);
},1000);
}
<div id="time1"></div>
<div id="time2"></div>
<button onclick="gotoMidnight();">goto 10 sec before midnight</button>

Changing Dates so They Are Within Business Hours

In a JavaScript step in Pentaho Data Integration, I want calculate the time in hours which passes between one date and another.
After following along with this this blog post, I realize that I need to adjust the startDate and endDate values in the function below which fall outside business hours so that they're within business hours so the function doesn't return zero. The dates are in the format 09/27/2018 18:54:55.
Here's my attempt so far:
var Approve_Gap;
var created_at_copy;
var approved_at_copy1;
// Function that accepts two parameters and calculates
// the number of hours worked within that range
function workingHoursBetweenDates(startDate, endDate) {
// Store minutes worked
var minutesWorked = 0;
// Validate input
if (endDate < startDate) { return 0; }
// Loop from your Start to End dates (by hour)
var current = startDate;
// Define work range
var workHoursStart = 8;
var workHoursEnd = 17;
var includeWeekends = true;
// bring dates into business hours
if(current.getHours() > workHoursEnd) {
current = current - (current.getHours() - workHoursEnd);
}
else if(current.getHours() < workHoursStart) {
current = current + (workHoursStart - current.getHours())
}
if(endDate.getHours() > workHoursEnd) {
endDate = endDate - (endDate.getHours() - workHoursEnd);
}
else if(endDate.getHours() < workHoursStart) {
endDate = endDate + (workHoursStart - endDate.getHours())
}
// Loop while currentDate is less than end Date (by minutes)
while(current <= endDate){
// Is the current time within a work day (and if it
// occurs on a weekend or not)
if(current.getHours() >= workHoursStart && current.getHours() < workHoursEnd && (includeWeekends ? current.getDay() !== 0 && current.getDay() !== 6 : true)){
minutesWorked++;
}
// Increment current time
current.setTime(current.getTime() + 1000 * 60);
}
// Return the number of hours
return minutesWorked / 60;
}
Approve_Gap = workingHoursBetweenDates(created_at_copy, approved_at_copy1);
I got the dates into business hours by adjusting copies of the dates as shown below:
if(created_at_copy.getHours() >= workHoursEnd) {
created_at_copy.setDate(created_at_copy.getDate() + 1);
created_at_copy.setHours(8);
created_at_copy.setMinutes(0);
created_at_copy.setSeconds(0);
} else if(created_at_copy.getHours() < workHoursStart) {
created_at_copy.setHours(8);
created_at_copy.setMinutes(0);
created_at_copy.setSeconds(0);
}
if(approved_at_copy1.getHours() >= (workHoursEnd)) {
approved_at_copy1.setDate(approved_at_copy1.getDate() + 1);
approved_at_copy1.setHours(8);
approved_at_copy1.setMinutes(0);
created_at_copy.setSeconds(0);
} else if(approved_at_copy1.getHours() < workHoursStart) {
approved_at_copy1.setHours(8);
approved_at_copy1.setMinutes(0);
created_at_copy.setSeconds(0);
}

Check if Saturday and Sunday exist between two days in Javascript [duplicate]

Wondering if anyone has a solution for checking if a weekend exist between two dates and its range.
var date1 = 'Apr 10, 2014';
var date2 = 'Apr 14, 2014';
funck isWeekend(date1,date2){
//do function
return isWeekend;
}
Thank you in advance.
EDIT Adding what I've got so far. Check the two days.
function isWeekend(date1,date2){
//do function
if(date1.getDay() == 6 || date1.getDay() == 0){
return isWeekend;
console.log("weekend")
}
if(date2.getDay() == 6 || date2.getDay() == 0){
return isWeekend;
console.log("weekend")
}
}
Easiest would be to just iterate over the dates and return if any of the days are 6 (Saturday) or 0 (Sunday)
Demo: http://jsfiddle.net/abhitalks/xtD5V/1/
Code:
function isWeekend(date1, date2) {
var d1 = new Date(date1),
d2 = new Date(date2),
isWeekend = false;
while (d1 < d2) {
var day = d1.getDay();
isWeekend = (day === 6) || (day === 0);
if (isWeekend) { return true; } // return immediately if weekend found
d1.setDate(d1.getDate() + 1);
}
return false;
}
If you want to check if the whole weekend exists between the two dates, then change the code slightly:
Demo 2: http://jsfiddle.net/abhitalks/xtD5V/2/
Code:
function isFullWeekend(date1, date2) {
var d1 = new Date(date1),
d2 = new Date(date2);
while (d1 < d2) {
var day = d1.getDay();
if ((day === 6) || (day === 0)) {
var nextDate = d1; // if one weekend is found, check the next date
nextDate.setDate(d1.getDate() + 1); // set the next date
var nextDay = nextDate.getDay(); // get the next day
if ((nextDay === 6) || (nextDay === 0)) {
return true; // if next day is also a weekend, return true
}
}
d1.setDate(d1.getDate() + 1);
}
return false;
}
You are only checking if the first or second date is a weekend day.
Loop from the first to the second date, returning true only if one of the days in between falls on a weekend-day:
function isWeekend(date1,date2){
var date1 = new Date(date1), date2 = new Date(date2);
//Your second code snippet implies that you are passing date objects
//to the function, which differs from the first. If it's the second,
//just miss out creating new date objects.
while(date1 < date2){
var dayNo = date1.getDay();
date1.setDate(date1.getDate()+1)
if(!dayNo || dayNo == 6){
return true;
}
}
}
JSFiddle
Here's what I'd suggest to test if a weekend day falls within the range of two dates (which I think is what you were asking):
function containsWeekend(d1, d2)
{
// note: I'm assuming d2 is later than d1 and that both d1 and d2 are actually dates
// you might want to add code to check those conditions
var interval = (d2 - d1) / (1000 * 60 * 60 * 24); // convert to days
if (interval > 5) {
return true; // must contain a weekend day
}
var day1 = d1.getDay();
var day2 = d2.getDay();
return !(day1 > 0 && day2 < 6 && day2 > day1);
}
fiddle
If you need to check if a whole weekend exists within the range, then it's only slightly more complicated.
It doesn't really make sense to pass in two dates, especially when they are 4 days apart. Here is one that only uses one day which makes much more sense IMHO:
var date1 = 'Apr 10, 2014';
function isWeekend(date1){
var aDate1 = new Date(date1);
var dayOfWeek = aDate1.getDay();
return ((dayOfWeek == 0) || (dayOfWeek == 6));
}
I guess this is the one what #MattBurland sugested for doing it without a loop
function isWeekend(start,end){
start = new Date(start);
if (start.getDay() == 0 || start.getDay() == 6) return true;
end = new Date(end);
var day_diff = (end - start) / (1000 * 60 * 60 * 24);
var end_day = start.getDay() + day_diff;
if (end_day > 5) return true;
return false;
}
FIDDLE
Whithout loops, considering "sunday" first day of week (0):
Check the first date day of week, if is weekend day return true.
SUM "day of the week" of the first day of the range and the number of days in the lap.
If sum>5 return true
Use Date.getDay() to tell if it is a weekend.
if(tempDate.getDay()==6 || tempDate.getDay()==0)
Check this working sample:
http://jsfiddle.net/danyu/EKP6H/2/
This will list out all weekends in date span.
Modify it to adapt to requirements.
Good luck.

How to exclude weekends between two dates using Moment.js

I am trying to exclude weekends in my JavaScript code. I use moment.js and having difficulty choosing the right variable for 'days'.
So far I have thought that I need to exclude day 6 (saturday) and day 0 (sunday) by changing the weekday variable to count from day 1 to day 5 only. But not sure how it changes.
My jsfiddle is shown here: FIDDLE
HTML:
<div id="myContent">
<input type="radio" value="types" class="syncTypes" name="syncTypes"> <td><label for="xshipping.xshipping1">Free Shipping: (<span id="fsv1" value="5">5</span> to <span id="fsv2" value="10">10</span> working days)</label> </td><br>
<div id="contacts" style="display:none;border:1px #666 solid;padding:3px;top:15px;position:relative;margin-bottom:25px;">
Contacts
</div>
<input type="radio" value="groups" class="syncTypes" name="syncTypes"> <td><label for="xshipping.xshipping2">Express Shipping: (<span id="esv1" value="3">3</span> to <span id="esv2" value="4">4</span> working days)</label> </td>
<div id="groups" style="display:none;border:1px #666 solid;padding:3px;top:15px;position:relative">
Groups
</div>
</div>
JavaScript:
var a = 5; //Free shipping between a
var b = 10;//and b
var c = 3;//Express shipping between c
var d = 4;//and d
var now = moment();
var f = "Your item will be delivered between " + now.add("days",a).format("Do MMMM") + " and " + now.add("days",b).format("Do MMMM");
var g = "Your item will be delivered between " + now.add("days".c).format("Do MMMM") + " and " + now.add("days",d).format("Do MMMM");
var h = document.getElementById('contacts');
h.innerHTML = g
var i = document.getElementById('groups');
i.innerHTML = f
$(function() {
$types = $('.syncTypes');
$contacts = $('#contacts');
$groups = $('#groups');
$types.change(function() {
$this = $(this).val();
if ($this == "types") {
$groups.slideUp(300);
$contacts.delay(200).slideDown(300);
}
else if ($this == "groups") {
$contacts.slideUp(300);
$groups.delay(200).slideDown(300);
}
});
});
Here you go!
function addWeekdays(date, days) {
date = moment(date); // use a clone
while (days > 0) {
date = date.add(1, 'days');
// decrease "days" only if it's a weekday.
if (date.isoWeekday() !== 6 && date.isoWeekday() !== 7) {
days -= 1;
}
}
return date;
}
You call it like this
var date = addWeekdays(moment(), 5);
I used .isoWeekday instead of .weekday because it doesn't depend on the locale (.weekday(0) can be either Monday or Sunday).
Don't subtract weekdays, i.e addWeekdays(moment(), -3) otherwise this simple function will loop forever!
Updated JSFiddle http://jsfiddle.net/Xt2e6/39/ (using different momentjs cdn)
Those iteration looped solutions would not fit my needs.
They were too slow for large numbers.
So I made my own version:
https://github.com/leonardosantos/momentjs-business
Hope you find it useful.
https://github.com/andruhon/moment-weekday-calc plugin for momentJS might be helpful for similar tasks
It does not solves the exact problem, but it is able to calculate specific weekdays in the range.
Usage:
moment().isoWeekdayCalc({
rangeStart: '1 Apr 2015',
rangeEnd: '31 Mar 2016',
weekdays: [1,2,3,4,5], //weekdays Mon to Fri
exclusions: ['6 Apr 2015','7 Apr 2015'] //public holidays
}) //returns 260 (260 workdays excluding two public holidays)
If you want a pure JavaScript version (not relying on Moment.js) try this...
function addWeekdays(date, days) {
date.setDate(date.getDate());
var counter = 0;
if(days > 0 ){
while (counter < days) {
date.setDate(date.getDate() + 1 ); // Add a day to get the date tomorrow
var check = date.getDay(); // turns the date into a number (0 to 6)
if (check == 0 || check == 6) {
// Do nothing it's the weekend (0=Sun & 6=Sat)
}
else{
counter++; // It's a weekday so increase the counter
}
}
}
return date;
}
You call it like this...
var date = addWeekdays(new Date(), 3);
This function checks each next day to see if it falls on a Saturday (day 6) or Sunday (day 0). If true, the counter is not increased yet the date is increased.
This script is fine for small date increments like a month or less.
I would suggest adding a function to the moment prototype.
Something like this maybe? (untested)
nextWeekday : function () {
var day = this.clone(this);
day = day.add('days', 1);
while(day.weekday() == 0 || day.weekday() == 6){
day = day.add("days", 1);
}
return day;
},
nthWeekday : function (n) {
var day = this.clone(this);
for (var i=0;i<n;i++) {
day = day.nextWeekday();
}
return day;
},
And when you're done and written some tests, send in a pull request for bonus points.
d1 and d2 are moment dates passed as an argument to calculateBusinessDays
calculateBusinessDays(d1, d2) {
const days = d2.diff(d1, "days") + 1;
let newDay: any = d1.toDate(),
workingDays: number = 0,
sundays: number = 0,
saturdays: number = 0;
for (let i = 0; i < days; i++) {
const day = newDay.getDay();
newDay = d1.add(1, "days").toDate();
const isWeekend = ((day % 6) === 0);
if (!isWeekend) {
workingDays++;
}
else {
if (day === 6) saturdays++;
if (day === 0) sundays++;
}
}
console.log("Total Days:", days, "workingDays", workingDays, "saturdays", saturdays, "sundays", sundays);
return workingDays;
}
If you want a version of #acorio's code sample which is performant (using #Isantos's optimisation) and can deal with negative numbers use this:
moment.fn.addWorkdays = function (days) {
// Getting negative / positive increment
var increment = days / Math.abs(days);
// Looping weeks for each full 5 workdays
var date = this.clone().add(Math.floor(Math.abs(days) / 5) * 7 * increment, 'days');
// Account for starting on Saturdays and Sundays
if(date.isoWeekday() === 6) { date.add(-increment, 'days'); }
else if(date.isoWeekday() === 7) { date.add(-2 * increment, 'days'); }
// Adding / removing remaining days in a short loop, jumping over weekends
var remaining = days % 5;
while(remaining != 0) {
date.add(increment, 'days');
if(date.isoWeekday() !== 6 && date.isoWeekday() !== 7)
remaining -= increment;
}
return date;
};
See Fiddle here: http://jsfiddle.net/dain/5xrr79h0/
Edit: now fixed issue adding 5 days to a day initially on a weekend
I know this question was posted long ago, but in case somebody bump on this, here is optimized solution using moment.js:
function getBusinessDays(startDate, endDate){
var startDateMoment = moment(startDate);
var endDateMoment = moment(endDate)
var days = Math.round(startDateMoment.diff(endDateMoment, 'days') - startDateMoment .diff(endDateMoment, 'days') / 7 * 2);
if (endDateMoment.day() === 6) {
days--;
}
if (startDateMoment.day() === 7) {
days--;
}
return days;
}
const calcBusinessDays = (d1, d2) => {
// Calc all days used including last day ( the +1 )
const days = d2.diff(d1, 'days') + 1;
console.log('Days:', days);
// how many full weekends occured in this time span
const weekends = Math.floor( days / 7 );
console.log('Full Weekends:', weekends);
// Subtract all the weekend days
let businessDays = days - ( weekends * 2);
// Special case for weeks less than 7
if( weekends === 0 ){
const cur = d1.clone();
for( let i =0; i < days; i++ ){
if( cur.day() === 0 || cur.day() === 6 ){
businessDays--;
}
cur.add(1, 'days')
}
} else {
// If the last day is a saturday we need to account for it
if (d2.day() === 6 ) {
console.log('Extra weekend day (Saturday)');
businessDays--;
}
// If the first day is a sunday we need to account for it
if (d1.day() === 0) {
console.log('Extra weekend day (Sunday)');
businessDays--;
}
}
console.log('Business days:', businessDays);
return businessDays;
}
This can be done without looping between all dates in between.
// get nb of weekend days
var startDateMonday = startDate.clone().startOf('isoWeek');
var endDateMonday = endDate.clone().startOf('isoWeek');
var nbWeekEndDays = 2 * endDateMonday.diff(startDateMonday, 'days') / 7;
var isoDayStart = startDate.isoWeekday();
if (isoDayStart > 5) // starts during the weekend
{
nbWeekEndDays -= (8 - isoDayStart);
}
var isoDayEnd = endDate.isoWeekday();
if (isoDayEnd > 5) // ends during the weekend
{
nbWeekEndDays += (8 - isoDayEnd);
}
// if we want to also exlcude holidays
var startOfStartDate = startDate.clone().startOf('day');
var nbHolidays = holidays.filter(h => {
return h.isSameOrAfter(startOfStartDate) && h.isSameOrBefore(endDate);
}).length;
var duration = moment.duration(endDate.diff(startDate));
duration = duration.subtract({ days: nbWeekEndDays + nbHolidays });
var nbWorkingDays = Math.floor(duration.asDays()); // get only nb of complete days
I am iterating from start date to end date and only counting days which are weekdays.
const calculateBusinessDays = (start_date, end_date) => {
const d1 = start_date.clone();
let num_days = 0;
while(end_date.diff(d1.add(1, 'days')) > 0) {
if ([0, 6].includes(d1.day())) {
// Don't count the days
} else {
num_days++;
}
}
return num_days;
}

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