I am trying to see if timeNow falls between a time range opening and closing :
var timeFormat2 = "HH:mm:ss";
var timeNow = "23:12:00"; //(11:12:00 pm)
var opening = "08:00:00"; //(08:00:00 am) morning time
var closing = "00:12:00"; //midnight time (i.e 12:12:00 am)
var isAvailable = moment(timeNow, timeFormat2).isBetween(moment(opening, timeFormat2), moment(closing, timeFormat2));
console.log("will show false >>>> ", isAvailable); //it shows 'false'
var closing1 = "23:45:00";
var isAvailable1 = moment("23:12:00", timeFormat2).isBetween(moment(opening, timeFormat2), moment(closing1, timeFormat2));
console.log("Should show true >>>> ", isAvailable1);
Here is a JSfiddle to check it out:
https://jsfiddle.net/1wuf0rzg/8/
You need to introduce the concept of "next day". Here I have set the date to be the first day of the month. If the closing time is before the opening time, then I move the closing time to the 2nd day of the month.
function isAvailable(opening, closing, now){
var openingTime = moment(opening, timeFormat2).date(1);
var closingTime = moment(closing, timeFormat2).date(1);
var nowTime = moment(now, timeFormat2).date(1);
if(closingTime.isBefore(openingTime)){
closingTime.date(2);
}
return nowTime.isBetween(openingTime, closingTime);
}
https://jsfiddle.net/1wuf0rzg/14/
There's not enough data to compute.
00:12:00 means 12 minutes less than 8 hours before the opening time of the current Date.
Because of that, 23:12:00will fall out of range.
It would help using different kind of data:
opening time.
working hours (amount).
time now,
in order to be able to determine - if the 'time now' falls inside the time interval with ease.
Related
I have a JavaScript/Math question.
I am stuck with one task for two days now and I guess I am complete idiot as I can't figure it out...Screenshot
I am creating a week calendar with shifts from 7am untill 8pm., but I can have shift which is for example 2 days long (or more).
The problem is that I can drag and drop the calendar event on the calendar and then I need to calculate new dateTo from dateFrom which I get from the div I placed it on.
The issues is that when I try to drag and drop the item to another time I need to place dateFrom to whenever I dragged it, but then I need to calculate hours so I get the same amount of time, but the problem is when the event is stretched over multiple days I need the event to finish next date after 7 am and not in the middle of the night. For example I had event from 3pm to 5pm of next day and then I moved it to 7pm of next day so I need the event to finish at 9 am of next day.
Does anyone has the same issue or solution for this?
Hope it makes sense, thank you very much.
Here is the code I am using right now, it almost works, but sometimes I get the wrong date/time (usually it removes 10 hours from date).
export function getCorrectDateAfterDrop(originalDateFrom, originalDateTo, dateFrom) {
const NIGHT_TIME = 11;
dateFrom = moment(dateFrom);
originalDateTo = moment(originalDateTo);
originalDateFrom = moment(originalDateFrom);
let hoursDiff = moment.duration(originalDateTo.diff(originalDateFrom)).asHours();
const sign = Math.sign(hoursDiff);
if (originalDateTo.isAfter(moment(originalDateFrom).hours(20))) {
hoursDiff = (hoursDiff > NIGHT_TIME) ? (hoursDiff - NIGHT_TIME) : hoursDiff;
}
let finalDateToBeChecked = moment(dateFrom).add((hoursDiff * sign), 'hours');
let isDateFromSameAsDateTo = moment(dateFrom).isSame(finalDateToBeChecked, 'day');
if (isDateFromSameAsDateTo && finalDateToBeChecked.hours() < 20) {
// I think the problem is here, but I can't figure it out :D
return finalDateToBeChecked.format();
} else {
const diffUntilShiftEnds = moment.duration(moment(dateFrom).hours(20).diff(dateFrom)).asHours();
hoursDiff -= diffUntilShiftEnds;
const finalDateFrom = moment(dateFrom).add(1, 'days').hours(7);
const finalDateTo = moment(dateFrom).add(1, 'days').hours(7).add(hoursDiff, 'hours');
return getCorrectDateAfterDrop(finalDateFrom, finalDateTo, finalDateFrom);
}
}
Maybe I do not fully understand your question, but I think something like the following should work:
function getCorrectDateAfterDrop(originalDateFrom, originalDateTo, dateFrom) {
return originalDateTo - originalDateFrom + dateFrom;
}
// verify it works:
var origFrom = Date.parse('01 Jan 2018 05:00:00');
var origTo = Date.parse('02 Jan 2018 07:00:00');
var newFrom = Date.parse('02 Jan 2018 01:00:00');
var newTo = getCorrectDateAfterDrop(origFrom, origTo, newFrom)
console.log((Date.parse('03 Jan 2018 03:00:00') === newTo)) // true
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
I am working on a simple Timesheet app, I am trying to implement an auto calculator that will sum up your hours for each day (Sunday, Monday, Tuesday, etc ...). A problem I noticed is that in some cases, users will enter activities that will be within the same date time periods.
For example:
$scope.Example = [
{Description:"Example activity",Start:"2018-06-24 8:00",End:"2018-06-24 10:00",Total:2},
{Description:"Example activity2",Start:"2018-06-24 9:00",End:"2018-06-24 10:00",Total:1},
{Description:"Example activity3",Start:"2018-06-24 10:00",End:"2018-06-24 11:00",Total:1}];
$scope.Calculate_all_entries = function(){
$scope.Total.Sunday = 0;
if($scope.Example){
angular.forEach($scope.Example, function(element){
if(moment(element.Start).format("dddd") === "Sunday"){
$scope.Total.Sunday = $scope.Total.Sunday + element.Total;
}
})
}
}
In this case the total should be 3 hours and not 4 hours as we dont charge for work within the same hours. I'm need to implement a system that would check if the dates are within the same period and provide the appropriate total.
I found this in the documentation on momentjs that seemed to be close to what i need but only takes one value:
moment('2010-10-19 11:00').isBetween('2010-10-19 10:00', '2010-10-25 00:00'); // true
Would anyone know of any other methods to check wether or not the start and end time are in the same period as other entries in the same day?
Sure, you can use momentjs's unix() function to convert those date times to an integer which then can easily be used to check whether the timestamp is in between two other timestamps.
Here is an example:
var timeToCheck = moment('2010-10-19 11:00').unix();
var startTime = moment('2010-10-19 10:00').unix();
var endTime = moment('2010-10-25 00:00').unix();
console.log(timeToCheck >= startTime && timeToCheck <= endTime); // true
I am working on programming a page in JS that grabs calendar data from an outside source, imports it into a multidimensional array and uses it to display who is currently working along with their photo, phone number, etc.
Right now I have it set up so that the page reloads every 15 minutes. I'd prefer to have this all done dynamically so that when, say, the clock strikes 5pm the page knows to update without having to wait until the 15 minute refresh is triggered.
All of the work times are pulled from the other calendar in 24 hour format (so 5pm is 1700).
Here's how I'm generating the current time to compare with the start/end times in the calendar:
//Get the current date and time
var dateTime = new Date();
var month = dateTime.getMonth() + 1;
var day = dateTime.getDate();
var dayOfWeek = dateTime.getDay();
var year = dateTime.getYear() + 1900;
//converting hours and minutes to strings to form the 24h time
var hours = dateTime.getHours().toString();
if (hours.length === 1) {
var hours = '0' + hours
};
var minutes = dateTime.getMinutes().toString();
if (minutes.length === 1) {
var minutes = '0' + minutes
};
var time = hours + minutes;
//convert the 24h time into a number to read from later
var timeNumber = parseInt(time);
I then use if statements to compare the start/end times from the imported schedule with timeNumber to determine who is currently working and push that to an array that is eventually displayed on the page with this code:
//figure out who is currently working and put them in the workingNow array
var workingNow = [];
for (i = 0; i < workingToday.length; i++){
//convert time strings to numbers to compare
var startTime = parseInt(workingToday[i][7]);
var endTime = parseInt(workingToday[i][8]);
//compare start and end times with the current time and add those who are working to the new list
if(startTime < timeNumber && timeNumber < endTime){
workingNow.push(workingToday[i]);
}
};
I guess I have just been trying to figure out how to make this comparison of the data in an array with the current time something that is dynamic. Is this possible or would I need to go about this in a completely different way from the ground up?
You should have a look at momentjs. This is a really good library to handle all sort of time and date manipulation.
http://momentjs.com/
So what I need to try an accomplish is to output a specific message depending on how close a date is. The task is to change an element of a webpage from a message saying "Renewal Unnecessary" when the date is more than 3 months away, "Renewal upcoming" when the date is less than 3 months away, and finally "Renewal Required!" when the date is 1 month away.
So far I have:
if()
{<hre>Renewal Required!</hre>}
else if()
{<ha>Renewal upcoming</ha>}
else
{<hg>Renewal Unnecessary</hg>}
I am uncertain of how to write the condition for what i need the script to do, for example the renewal month or date might be the 26th February, and is there some way of making it work off the computers date.
Date.now returns currrent date in miliseconds. Just check for
renewal_date - Date.now()
And compare it with the corrent number of miliseconds.
Here's one way you could do it. You could expand this to be considerate of what day of the month it is, also. Live demo (click).
var deadline = new Date(2014, 1, 2); //2014, February 2nd (January is Month 0)
var today = new Date();
var monthDiff = deadline.getMonth() - today.getMonth();
if (monthDiff < 3) {
console.log('Deadline is in 3 months or less!');
}
if (monthDiff <= 1) {
console.log('Deadline is in 1 month or less!');
}
Answering your comment: There a are lots of ways this can be done - learn the basics. Here are two examples that might help.
var p = document.createElement('p);
p.textContent = 'My message here';
document.body.appendChild(p);
Or if the element already exists on the page:
var elem = document.getElementById('myElem');
elem.textContent = 'My message here';
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.