checking new time valid within a fixed time using javascript - javascript

I have created a function in javascript to check if the time is valid or not, i.e if the new time (has start and end time) is in between a fixed time (has start and end time), it is valid, otherwise invalid.
Working JSFiddle
My code is as given below
Here it is giving valid when i give invalid times
var fixedTime = {start : '2014-11-13T09:00:00', end : '2014-11-13T13:00:00'};
var newTime = {start : '2014-11-13T06:30:00', end : '2014-11-13T08:30:00'};
if(checkDates(fixedTime, newTime))
{
window.alert("Valid");
}
else
{
window.alert("Invalid");
}
function checkDates(fixedTime, newTime)
{
var returnBoolean = true;
if(((new Date(newTime.start).getTime()) <= (new Date(fixedTime.start).getTime()) && (new Date(newTime.start).getTime()) >= (new Date(fixedTime.end).getTime())) || ((new Date(newTime.end).getTime()) <= (new Date(fixedTime.start).getTime()) && (new Date(newTime.end).getTime()) >= (new Date(fixedTime.end).getTime())))
{
returnBoolean = false;
}
return returnBoolean;
}
can anyone please tell me some solutions for this

No need for such enormous complexity. You only need to make two comparisons:
var fixedTime = {
start: new Date('2014-11-13T09:00:00').getTime(),
end: new Date('2014-11-13T13:00:00').getTime()
};
var newTime = {
start: new Date('2014-11-13T06:30:00').getTime(),
end: new Date('2014-11-13T08:30:00').getTime()
};
if (checkDates(fixedTime, newTime)) {
alert("Valid");
} else {
alert("Invalid");
}
function checkDates(fixedTime, newTime) {
return newTime.start > fixedTime.start && newTime.end < fixedTime.end;
}
Fiddle

Related

To sort array based on startdtate and present job or no

I am making a dynamic portfolio for myself using VueJS.
I created a way to update experiences and order it based on currently ongoing jobs showing first sorted in ascending order meaning a job with start date May 2021 will show first and then March 2021 (both being present).
Next, if I set an end date for the job, it should update and place the current jobs in the front which isn't happening.
Algorithm:
newExp() {
this.editableExperience.sort((a,b) => {
a = a.period.split(' - ');
b = b.period.split(' - ');
let aStartDate = a[0];
let aEndDate = a[1];
let bStartDate = b[0];
let bEndDate = b[1];
if (aEndDate == 'Present' && bEndDate == 'Present') {
return new Date(bStartDate) - new Date(aStartDate);
} else if (aEndDate == 'Present') {
return a;
} else if (bEndDate == 'Present') {
return b;
} else {
return new Date(bStartDate) - new Date(aStartDate);
}
})
this.experience = this.editableExperience;
}
editableExperience is an array of experiences: (I have added only required information)
editableExperience = [{period: 'May 2021 - Present'}, {period: 'November 2020 - Present'}, {period: 'January 2021 - March 2021'}, {period: 'March 2018 - July 2020'}]
Exact issue situation:
Setting the third element to present job brings it to position 2 but giving it an end date again does not send it to position 3 again.
Setting the last element to present does not bring it in front of the non-present jobs.
Your compare function is returning a string or a number while the compare function should return either 1, 0 or -1 as per the MDN docs.
I have made changes to your code below:
newExp() {
this.editableExperience.sort((a,b) => {
a = a.period.split(' - ');
b = b.period.split(' - ');
let aStartDate = a[0];
let aEndDate = a[1];
let bStartDate = b[0];
let bEndDate = b[1];
if (aEndDate == 'Present' && bEndDate == 'Present') {
return (new Date(bStartDate) - new Date(aStartDate)) > 1 ? 1 : -1;
} else if (aEndDate == 'Present') {
return -1;
} else if (bEndDate == 'Present') {
return 1;
} else {
return (new Date(bStartDate) - new Date(aStartDate)) > 1 ? 1 : -1;
}
});
this.experience = this.editableExperience;
}
The view model is a little bit mixed with data model, I would suggest to keep a clean data model which hold the original values, it is good for processing like sort. then a a computed property as view model which is depend on the data model.
data: () => ({
editableExperience: [
{start: 202105, end: 999999},
{start: 202011, end: 999999},
{start: 202101, end: 202103},
{start: 201803, end: 202107},
],
}),
then the sorting will looks like:
this.editableExperience.sort((a,b) => {
return b['end'] === a['end']? b['start'] - a['start'] : b['end'] - a['end']
})
for your view(display)
computed: {
viewExperiences() {
const ve = []
for(const e of this.editableExperience) {
ve.push(this.getExperienceDisplay(e))
}
return ve
}
},
methods: {
formatExperienceDate(dateInt) {
if(dateInt === 999999) return 'Present'
const dateStr = dateInt.toString()
const date = new Date(dateStr.substring(0, 4) + '-' + dateStr.substring(4, 6))
return date.toLocaleDateString("en-US", {year: 'numeric', month: 'long'})
},
getExperienceDisplay(exp) {
const startDate = this.formatExperienceDate(exp['start'])
const endDate = this.formatExperienceDate(exp['end'])
return `${startDate} - ${endDate}`
},
}

clearInterval does not stop the interval operation

I'm working on a timer, and would like the setInterval() operation to terminate when the counter reaches zero. Further, I would like the function to be "turned off" if you will, so that I can reset the value that is fed into the timer, without the timer starting to decrement again.
When I configure the code like this:
function countdown(){
var intervalKill = setInterval(function(){
var start = document.getElementById("startValue").innerHTML;
if (start > 1){
var time_left = start - 1;
document.getElementById("startValue").innerHTML = time_left;
} else if (start === 1) {
clearInterval(intervalKill)
}
}, 1000);
}
I get it running perfectly well, however if it reaches 1, and I reset the timer, it will start counting down instantly again.
When I code it like this:
function countdown(){
var intervalKill = setInterval(function(){
var start = document.getElementById("startValue").innerHTML;
if (start > 1){
var time_left = start - 1;
document.getElementById("startValue").innerHTML = time_left;
} else if (start === 1) {
clearInterval(intervalKill);
break;
}
}, 1000);
}
The function just does not run at all. Can someone shed some light on what is going on here and how to get it to work?
function countdown(){
var intervalKill = setInterval(function(){
var start = document.getElementById("startValue").innerHTML;
if (start > 1){
var time_left = start - 1;
document.getElementById("startValue").innerHTML = time_left;
} else if (+start === 1) {
clearInterval(intervalKill);
// break; <-- not necessary
}
}, 1000);
}
Either parse the start to integer using unary + or parseInt or use == instead of === since the latter checks for type information as well.
innerHTML returns a string.

How do I get the current school hour and time remaining?

I have this function:
function getInfoSchoolTime() {
var date = new Date();
var schoolBellTime = ["8:10","9:02","9:54","9:59","10:51","11:43","11:58","12:48","13:35","13:40","14:10","15:02","15:54"];
var remainingTime, currentHour;
for (var i = 0; i < schoolBellTime.length-1; i++) {
var startTime = schoolBellTime[i].split(":");
var endTime = schoolBellTime[i+1].split(":");
if (parseInt(startTime[0]) >= date.getHours() && parseInt(startTime[1]) >= date.getMinutes())
if (parseInt(endTime[0]) <= date.getHours() && parseInt(endTime[1]) <= date.getMinutes()) {
currentHour = i;
remainingTime=(parseInt(endTime[1])-date.getMinutes()+60)%60;
break;
}
}
if (currentHour == undefined)
return {current: -1, remaining: "not available"};
return {current: currentHour, remaining: remainingTime};
}
var info = getInfoSchoolTime();
console.log(info.current, info.remaining);
I have the schoolBellTime array that contains the timestamps of my school bell (I know, my school has strange bell times, these timestamps includes playtimes and lunchtime), this function is meant to return the 1st hour/2nd hour/3rd hour ... and the minutes that remains to the next hour/breaktime.
I checked all the code and can't find the error, it keeps returning {current: -1, remaining: "not available"}
The function at the top: setDateTime() takes a date and a time, and constructs a date object for that time.
Then I updated your function, I convert start and end to times on the current day, and then check if date.getTime() occurs between them. Then I simply subtract date.getTime() from end, and convert the result to minutes from milliseconds.
var setDateTime = function(date, str) {
var sp = str.split(':');
date.setHours(parseInt(sp[0], 10));
date.setMinutes(parseInt(sp[1], 10));
return date;
}
function getInfoSchoolTime() {
var date = new Date();
var schoolBellTime = ["8:10", "9:02", "9:54", "9:59", "10:51", "11:43", "11:58", "12:48", "13:35", "13:40", "14:10", "14:10", "15:02", "15:54"];
var remainingTime, currentHour, currentPeriod;
for (var i = 0; i < schoolBellTime.length - 1; i++) {
start = setDateTime(new Date(), schoolBellTime[i])
end = setDateTime(new Date(), schoolBellTime[i + 1])
if (date.getTime() > start.getTime() && date.getTime() < end.getTime()) {
currentHour = i
remainingTime = end.getTime() - date.getTime()
currentPeriod = ([schoolBellTime[i], schoolBellTime[i+1]]).join('-')
}
}
return {current: currentHour, currentPeriod: currentPeriod, remaining: Math.round(remainingTime * 0.0000166667)}
}
console.log(getInfoSchoolTime())
Here's a somewhat different approach, both to the code and the API. It uses two helper functions. Each should be obvious with a single example: pad(7) //=> "07" and pairs(['foo', 'bar', 'baz', 'qux']) //=> [['foo', 'bar'], ['bar', 'baz'], ['baz', 'qux']].
The main function takes a list of bell times and returns a function which itself accepts a date object and returns the sort of output you're looking for (period, remaining time in period.) This API makes it much easier to test.
const pad = nbr => ('00' + nbr).slice(-2)
const pairs = vals => vals.reduce((res, val, idx) => idx < 1 ? res : res.concat([[vals[idx - 1], val]]), [])
const schoolPeriods = (schoolBellTime) => {
const subtractTimes = (t1, t2) => 60 * t1.hour + t1.minute - (60 * t2.hour + t2.minute)
const periods = pairs(schoolBellTime.map(time => ({hour: time.split(':')[0], minute: +time.split(':')[1]})))
return date => {
const current = {hour: date.getHours(), minute: date.getMinutes()}
if (subtractTimes(current, periods[0][0]) < 0) {
return {message: 'before school day'}
}
if (subtractTimes(current, periods[periods.length - 1][1]) > 0) {
return {message: 'after school day'}
}
const idx = periods.findIndex(period => subtractTimes(current, period[0]) >= 0 && subtractTimes(period[1], current) > 0)
const period = periods[idx]
return {
current: idx + 1,
currentPeriod: `${period[0].hour}:${pad(period[0].minute)} - ${period[1].hour}:${pad(period[1].minute)}`,
remaining: subtractTimes(period[1], current)
}
}
}
const getPeriod = schoolPeriods(["8:10","9:02","9:54","9:59","10:51","11:43","11:58","12:48","13:35","13:40","14:10","14:10","15:02","15:54"])
console.log("Using current time")
console.log(getPeriod(new Date()))
console.log("Using a fixed time")
console.log(getPeriod(new Date(2017, 11, 22, 14, 27))) // will Christmas break ever come?!
I made a random guess at the behavior you would want if the date is outside the period range.
Internally, it creates a list of period objects that look like
[{hour:9, minute: 59}, {hour: 10, minute: 51}]
Perhaps it would be cleaner if instead of a two-element array it was an object with start and end properties. That would be an easy change.
Do note that for this to make sense, the bells need to be listed in order. We could fix this with a sort call, but I don't see a good reason to do so.
Here is an ES6 example using deconstruct (const [a,b]=[1,2]), array map, array reduce, partial application (closure) and fat arrow function syntax.
This may not work in older browsers.
//pass date and bellTimes to function so you can test it more easily
// you can partially apply bellTimes
const getInfoSchoolTime = bellTimes => {
//convert hour and minute to a number
const convertedBellTimes = bellTimes
.map(bellTime=>bellTime.split(":"))//split hour and minute
.map(([hour,minute])=>[new Number(hour),new Number(minute)])//convert to number
.map(([hour,minute])=>(hour*60)+minute)//create single number (hour*60)+minutes
.reduce(//zip with next
(ret,item,index,all)=>
(index!==all.length-1)//do not do last one, create [1,2][2,3][3,4]...
? ret.concat([[item,all[index+1]]])
: ret,
[]
);
return date =>{
//convert passed in date to a number (hour*60)+minutes
const passedInTime = (date.getHours()*60)+date.getMinutes();
return convertedBellTimes.reduce(
([ret,goOn],[low,high],index,all)=>
//if goOn is true and passedInTime between current and next bell item
(goOn && passedInTime<high && passedInTime>=low)
? [//found the item, return object and set goOn to false
{
current: index+1,
currentPeriod: bellTimes[index]+"-"+bellTimes[index+1],
remaining: high-passedInTime
},
false//set goOn to false, do not continue checking
]
: [ret,goOn],//continue looking or continue skipping (if goOn is false)
[
{current: 0, currentPeriod: "School is out", remaining: 0},//default value
true//initial value for goOn
]
)[0];//reduced to multiple values (value, go on) only need value
}
};
//some tests
const date = new Date();
//partially apply with some bell times
const schoolTime = getInfoSchoolTime(
[
"8:10", "9:02", "9:54", "9:59", "10:51",
"11:43", "11:58", "12:48", "13:35", "13:40",
"14:10", "14:10", "15:02", "15:54"
]
);
//helper to log time from a date
const formatTime = date =>
("0"+date.getHours()).slice(-2)+":"+("0"+date.getMinutes()).slice(-2);
date.setHours(11);
date.setMinutes(1);
console.log(formatTime(date),schoolTime(date));//11:01
date.setHours(15);
date.setMinutes(53);
console.log(formatTime(date),schoolTime(date));//15:53
date.setHours(23);
date.setMinutes(1);
console.log(formatTime(date),schoolTime(date));//23:01

JavaScript check if time ranges overlap

I have e.g. an array with 2 objects (myObject1 and myObject2 like ).
Now when I add an third object I will check if time range overlaps.
Actually I don't know how I can do this in a performant way.
var myObjectArray = [];
var myObject1 = {};
myObject1.startTime = '08:00';
myObject1.endTime = '12:30';
...
var myObject2 = {};
myObject2.startTime = '11:20';
myObject2.endTime = '18:30';
...
myObjectArray.push(myObject1);
myObjectArray.push(myObject2);
Let assume we have some intervals
const INTERVALS = [
['14:00', '15:00'],
['08:00', '12:30'],
['12:35', '12:36'],
['13:35', '13:50'],
];
If we want to add new interval to this list we should check if new interval is not overlapping with some of them.
You can loop trough intervals and check if the new one is overlapping with others. Note that when comparing intervals you do not need Date object if you are sure it is the same day as you can convert time to number:
function convertTimeToNumber(time) {
const hours = Number(time.split(':')[0]);
const minutes = Number(time.split(':')[1]) / 60;
return hours + minutes;
}
There are two cases where intervals are NOT overlapping:
Before (a < c && a < d) && (b < c && b <d):
a b
|----------|
c d
|----------|
After where (a > c && a > d) && (b > c && b > d):
a b
|----------|
c d
|----------|
Because always c < d, it is enough to say that condition for NOT overlapping intervals is (a < c && b < c) || (a > d && b > d) and because always a < b, it is enough to say that this condition is equivalent to:
b < c || a > d
Negation of this condition should give us a condition for overlapping intervals. Base on De Morgan's laws it is:
b >= c && a <= d
Note that in both cases, intervals can not "touch" each other which means 5:00-8:00 and 8:00-9:00 will overlap. If you want to allow it the condition should be:
b > c && a < d
There are at least 5 situation of overlapping intervals to consider:
a b
|----------|
c d
|----------|
a b
|----------|
c d
|----------|
a b
|----------|
c d
|--------------------|
a b
|--------------------|
c d
|----------|
a b
|----------|
c d
|----------|
Full code with extra add and sort intervals functions is below:
const INTERVALS = [
['14:00', '15:00'],
['08:00', '12:30'],
['12:35', '12:36'],
['13:35', '13:50'],
];
function convertTimeToNumber(time) {
const hours = Number(time.split(':')[0]);
const minutes = Number(time.split(':')[1]) / 60;
return hours + minutes;
}
// assuming current intervals do not overlap
function sortIntervals(intervals) {
return intervals.sort((intA, intB) => {
const startA = convertTimeToNumber(intA[0]);
const endA = convertTimeToNumber(intA[1]);
const startB = convertTimeToNumber(intB[0]);
const endB = convertTimeToNumber(intB[1]);
if (startA > endB) {
return 1
}
if (startB > endA) {
return -1
}
return 0;
})
}
function isOverlapping(intervals, newInterval) {
const a = convertTimeToNumber(newInterval[0]);
const b = convertTimeToNumber(newInterval[1]);
for (const interval of intervals) {
const c = convertTimeToNumber(interval[0]);
const d = convertTimeToNumber(interval[1]);
if (a < d && b > c) {
console.log('This one overlap: ', newInterval);
console.log('with interval: ', interval);
console.log('----');
return true;
}
}
return false;
}
function isGoodInterval(interval) {
let good = false;
if (interval.length === 2) {
// If you want you can also do extra check if this is the same day
const start = convertTimeToNumber(interval[0]);
const end = convertTimeToNumber(interval[1]);
if (start < end) {
good = true;
}
}
return good;
}
function addInterval(interval) {
if (!isGoodInterval(interval)) {
console.log('This is not an interval');
return;
}
if (!isOverlapping(INTERVALS, interval)) {
INTERVALS.push(interval);
// you may also want to keep those intervals sorted
const sortedIntervals = sortIntervals(INTERVALS);
console.log('Sorted intervals', sortedIntervals);
}
}
// --------------------------------------
const goodIntervals = [
['05:31', '06:32'],
['16:00', '17:00'],
['12:31', '12:34']
];
let goodCount = 0;
for (const goodInterval of goodIntervals) {
if (!isOverlapping(INTERVALS, goodInterval)) {
goodCount += 1
}
}
console.log('Check good intervals: ', goodCount === goodIntervals.length);
// --------------------------------------
const ovelappingIntervals = [
['09:30', '12:40'],
['05:36', '08:50'],
['13:36', '13:37'],
['06:00', '20:00'],
['14:00', '15:00']
]
let badCount = 0;
for (const badInterval of ovelappingIntervals) {
if (isOverlapping(INTERVALS, badInterval)) {
badCount += 1
}
}
console.log('Check bad intervals: ', badCount === ovelappingIntervals.length);
// --------------------------------------
addInterval(goodIntervals[0])
You can try something like this:
var timeList = [];
function addTime() {
var startTime = document.getElementById("startTime").value;
var endTime = document.getElementById("endTime").value;
if (validate(startTime, endTime)){
timeList.push({
startTime: startTime,
endTime: endTime
});
print(timeList);
document.getElementById("error").innerHTML = "";
}
else
document.getElementById("error").innerHTML = "Please select valid time";
}
function validate(sTime, eTime) {
if (+getDate(sTime) < +getDate(eTime)) {
var len = timeList.length;
return len>0?(+getDate(timeList[len - 1].endTime) < +getDate(sTime) ):true;
} else {
return false;
}
}
function getDate(time) {
var today = new Date();
var _t = time.split(":");
today.setHours(_t[0], _t[1], 0, 0);
return today;
}
function print(data){
document.getElementById("content").innerHTML = "<pre>" + JSON.stringify(data, 0, 4) + "</pre>";
}
<input type="text" id="startTime" />
<input type="text" id="endTime" />
<button onclick="addTime()">Add Time</button>
<p id="error"></p>
<div id="content"></div>
Use moment-js with moment-range (broken reference)
Tested example:
const range1 = moment.range(a, c);
const range2 = moment.range(b, d);
range1.overlaps(range2); // true
See more examples in https://github.com/rotaready/moment-range#overlaps
Note, for the above code to work maybe you first do:
<script src="moment.js"></script>
<script src="moment-range.js"></script>
window['moment-range'].extendMoment(moment);
HTML code
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/2.2.0/moment-range.min.js"></script>
JavaScript code
var range = moment.range(new Date(year, month, day, hours, minutes), new Date(year, month, day, hours, minutes));
var range2 = moment.range(new Date(year, month, day, hours, minutes), new Date(year, month, day, hours, minutes));
range.overlaps(range2); // true or flase
Pretty neat solution and momentjs comes with tons of date and time utilities.
Use JavaScript Date() object to store time and then compare them if ending time of object1 is greater than starting time of object2 then they are overlapping.
You can compare them using > operator.
date1.getTime() > date2.getTime()
Demonstration given here
Usage of Date object
To determine whether the time range overlaps other time ranges you can utilize both moment.js and moment-range libraries.
First install moment-js and moment-range
Given you have an INTERVALS array that contains example objects:
const INTERVALS = [
{ START: 0, END: 10 },
{ START: 12, END: 30 },
...
]
You can use a function below:
const validateIntervalOverlaps = () => {
if (INTERVAL_START && INTERVAL__END) {
const timeInterval = moment.range(moment(INTERVAL_START), moment(INTERVAL_ENDS))
const overlappingInterval = INTERVALS.find(intervalItem => {
const interval = moment.range(moment(intervalItem.START), moment(intervalItem.END))
return timeInterval.overlaps(interval)
})
return overlappingInterval
}
}
Next, you can do what you need to do with overlappingInterval :) F.e. determine if it exists or use it in any other way. Good luck!
Here's something that might work.
// check if time overlaps with existing times
for (var j = 0; j < times.length; j++) {
let existing_start_time = moment(this.parseDateTime(this.times[j].start_time)).format();
let existing_end_time = moment(this.parseDateTime(this.times[j].end_time)).format();
// check if start time is between start and end time of other times
if (moment(start_time).isBetween(existing_start_time, existing_end_time)) {
times[i].error = 'Time overlaps with another time';
return false;
}
// check if end time is between start and end time of other times
if (moment(end_time).isBetween(existing_start_time, existing_end_time)) {
times[i].error = 'Time overlaps with another time';
return false;
}
}
https://momentjs.com/
You can check if there is an overlap by trying to merge a time range to the existing time ranges, if the total count of time ranges decrease after merge, then there is an overlap.
I found following articles which might help on handle merging ranges
Merge arrays with overlapping values
merge-ranges

Trouble with returning value from function

Please, look at this code and tell me why doesn't work? i think that there is a problem with return in function. Thanks for all replays.
var movie1 = {
title: "Buckaroo Banzai",
genre: "Cult classic",
rating: 5,
showtimes: ["1:00pm", "3:00pm", "7:00pm"]
}
function getNextShowing(movie) {
var now = new Date().getTime();
for (var i = 0; i < movie.showtimes.length; i++) {
var showtime = getTimeFromString(movie.showtimes[i]);
if ((showtime - now) > 0) {
return "Next showing of " + movie.title + " is " + movie.showtimes[i];
}
}
return null;
}
function getTimeFromString(timeString) {
var theTime = new Date();
var time = timeString.match(/(\d+)(?::(\d\d))?\s*(p?)/);
theTime.setHours( parseInt(time[1]) + (time[3] ? 12 : 0) );
theTime.setMinutes( parseInt(time[2]) || 0 );
return theTime.getTime();
}
var nextShowing = getNextShowing(movie1);
alert(nextShowing);
The issue is with this line of code:
if ((showtime - now) > 0)
(showtime - now) is always less than zero therefore the getNextShowing() function always returns null;
I tested the above code, and it only returned me a null when the time in my computer is greater than or equal to 7:00pm.
Otherwise it works fine. Try changing the timing of the showtimes array, so that they are ahead of current time in your computer. Or try running it during the morning :).
I think that is all you need to do.

Categories

Resources