compare start "Time" is less than the end "Time" in javascript - javascript

I have a value in two text fields which is already formatted as hh:mm, How can I compare the values of these two fields?
I am trying the following code:
function check_ToFromTime(toTime) {
if (getControl('txtStartTimeFrom').value == '00:00' && getControl(toTime).value == '00:00') { return true; }
var fromDate = new Date(getControl('txtStartTimeFrom').value);
var toDate = new Date(getControl('txtEndTimeTo').value);
var fromT = fromDate.getTime();
var toT = toDate.getTime();
return (toT >= fromT);
}
the if statement in the first line works, but the last statement
return (toT >= fromT);
does not work. it always returns false. where am i going wrong?

I wouldn't worry about converting these String objects to Date objects. Just split the string and compare:
var fromDate = "04:05";
var toDate = "04:04";
var fromTokens = fromDate.split(":");
var toTokens = toDate.split(":");
alert(fromTokens[0] < toTokens[0] || (fromTokens[0] == toTokens[0] && fromTokens[1] < toTokens[1]));
You could place this functionality in a nice function for re-usability:
function isAfter(fromDate, toDate){
var fromTokens = fromDate.split(":");
var toTokens = toDate.split(":");
return (fromTokens[0] < toTokens[0] || (fromTokens[0] == toTokens[0] && fromTokens[1] < toTokens[1]));
}
//Tests
alert(isAfter("04:04", "05:05"));
alert(isAfter("06:04", "05:05"));
alert(isAfter("05:05", "05:05"));
JS Fiddle: http://jsfiddle.net/X5v5F/
I'm not going to head down this route, since I think splitting the strings is sufficient, but if you were fixed on a date, I would recommend using Moment.js.

it will always print false because end time will always be greater than start time.U need to change the condition i.e. return (toT <= fromT);

Related

Check if time range overlaps with another time range

Assume i have a start date and a end data as follows
end: "2021-10-22T06:00:00.000Z"
start: "2021-10-22T05:00:00.000Z"
I want to check if another given time range overlaps with the above time range in javascript. I tried using moment as follows.
return (
moment(timerange1.duration.end) <= moment(timerange2.duration.start) ||
moment(timerange1.duration.start) >= moment(timerange2.duration?.end)
);
But this does not produce the correct results. What would be the correct way to check if a certain time range overlaps with another time range using javascript?
Consider this:
In case A and C they do not overlap.
But what is true in B that isn't true in A or C?
Well, the start, or the end of the red one, is between the start and end of the blue one. That will always be true for overlapping timeperiods.
Example code:
if( (red.start > blue.start && red.start < blue.end) || (red.end > blue.start && red.end< blue.end) ) {
// do something
}
return (
(moment(timerange1.duration.start) >= moment(timerange2.duration.start) && moment(timerange1.duration.start) <= moment(timerange2.duration.end))
|| (moment(timerange1.duration.end) >= moment(timerange2.duration.start) && moment(timerange1.duration.end) <= moment(timerange2.duration.end))
|| (moment(timerange2.duration.start) >= moment(timerange1.duration.start) && moment(timerange2.duration.start) <= moment(timerange1.duration.end))
)
there are 3 different cases to consider as overlap
timerange1: |-----|
timerange2:     |-----|
timerange1:     |-----|
timerange2: |-----|
timerange1: |-----------|
timerange2:     |-----|
You can use the twix.js plugin for moment to handle the date ranges. In your code, you need to do something like that. This is sample code snippet you can modify it according to your need.
var t1 = {
start: "1982-01-25T09:30",
end: "1982-01-25T13:30",
};
var t2 = {
start: "1982-01-23T13:30",
end: "1982-01-25T12:30",
};
var t3 = {
start: "1982-01-24T13:30",
end: "1982-01-25T10:30",
};
var t1Range = moment(t1.start).twix(t1.end);
var t2Range = moment(t2.start).twix(t2.end);
var t3Range = moment(t3.start).twix(t3.end);
t1Range.overlaps(t2Range) || t1Range.overlaps(t3Range); //=> true

How do I mask an email address between the first and the last character before the # sign?

My goal is to edit the string (which has an email) to mask the first part, like say the email is johndoe#abc.com then I should output j*****e#abc.com.
var maskPII = function(S) {
var ans = "";
if(S.includes("#")){
S = S.toLowerCase();
var parts = S.split("#");
var first = parts[0];
for(var i=0;i<parts[0].length;i++){
if(i!=0 && i!=parts[0].length - 1)
first[i] = '*';
}
ans = first +"#" +parts[1];
}else{
}
return ans;
};
However in my loop I can't change the characters to asterisks.
After execution I see value of first still same as parts[0] and has no asterisks, can some one explain why? Also, what would I need to do to modify the variable inside loop?
To answer your question... javascript allows you access values of a string using [] indexing.. but that is read only access... you cannot insert/replace values using that operator.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
When using bracket notation for character access,
attempting to delete or assign a value to these properties will not succeed.
The properties involved are neither writable nor configurable.
(See Object.defineProperty() for more information.)
You need to extract the values you want to keep from the existing string and build up a new string as noted in other answers...
Well, this's what you're looking for, and this will be the output j*****e#abc.com.
var ans = "";
var S = "johndoe#abc.com"; //example
S = S.toLowerCase();
var parts = S.split("#");
var first = "";
for(var i = 0; i < parts[0].length; i++){
if(i != 0 && i != parts[0].length - 1){
first += '*';
}else{
first += parts[0][i];
}
}
ans = first +"#"+ parts[1];
console.log(ans);
Here is the code with your approach:
var maskPII = function(S) {
var ans = "";
if(S.includes("#")){
S = S.toLowerCase();
var parts = S.split("#");
var first = parts[0][0];
for(var i=0;i<parts[0].length;i++){
if(i!=0 && i!=parts[0].length - 1)
first += '*';
}
ans = first + parts[0][parts[0].length - 1] +"#" +parts[1];
}else{
}
return ans;
};
But if i were you i would use:
var mail = "johndoe#abc.com";
mail = mail.replace(/(?<=.)(.+?)(?=.#)/gi, '*'.repeat(mail.split('#')[0].length - 2));
console.log(mail);
You can use the bracket notation on a string (like an array) to get the character at a specific index, but you can't use this to change characters. So first[i] = '*' in your code wont do anything.
Strings in JavaScript are immutable. This means that if you want to change a string, a new string instance will be created. This also means that when you change a string in a for-loop, it can impact performance. (Although in this case the difference wont be noticeable.
)
I would use this code:
function maskPII(str) {
const indexOfAt = str.indexOf('#');
if (indexOfAt <= 2) {
return str;
}
return str[0] + '*'.repeat(indexOfAt - 2) + str.substring(indexOfAt - 1);
}
const email = 'johndoe#abc.com';
console.log(email);
console.log(maskPII(email));
It will look for the index of the # sign. If the index is less or equal than 2, (when not found the index will be -1) it will return the original string.
Otherwise it will get the first character, calculate the amount of asterisks needed (index of the # sign -2) and repeat those and then add the rest of the original string.

data range in TypeScript

Update:
I have several objects with start dates and end date
When inserting / modifying an object, the starting or ending date of the new object can not be included in the existing object.
Exist : 06/06/2018-----30/06/2018
can input:
04/06/2018-------05/06/2018
02/02/2018------ until less than date Start of which exists (05/06/2018)
or higher:
31/06/2018--------
can not get in :
04/06/2018-------07/06/2018 The end is already understood between the beginning and the end exists.
Or
07/06/2018---08/06/2018 because it is also included between the beginning and the end of the.
Code:
validateParamsDates(url, newConfig) {
return this.http.get<any>(url).pipe(map(param => {
let messageError = { message: "", showAlert: false };
let userStart = newConfig.startdatevalidity;
let userFinish = newConfig.enddatevalidity;
param[1]['params'].array.forEach(element => {
if(userStart > element.startdatevalidity && userFinish > element.enddatevalidity
|| userStart < element.startdatevalidity && userFinish < element.enddatevalidity
&& userStart > element.enddatevalidity
){
console.log('good');
}else{
console.log('=(');
}
});
return messageError ;
}));
}
You should first convert the strings to a Date object. Then you can compare dates and everything will work as it should ;)
So you would do something like:
const start2: Date = new Date(Object2.start);
const end1: Date = new Date(Object1.end);
if (start2 > end1) { console.log('good'); }
Please also note that in order for all of this to work in javascript, the dates should be defined in MM/DD/YYYY format not in DD/MM/YYYY
I would probably do something like this.
var start = new Date(Object2.start);
var end = new Date(Object1.end);
if(start.getTime() > end.getTime()) console.log('good');
Similar to this answer: Compare two dates with JavaScript

Comparision between 2 Object

I am working on a course registration system.I need to check for time conflicts.
Already registered courses object:
{"00001":{"days":"Monday-Tuesday","hours":"11:40-12:30*13:40-15:30"}}
this means that 00001 course is in monday 11:40-12:30 in tuesday 13:40-15:30
Courses to register object:
{"00003":{"days":"Friday","hours":"9:40-10:40"}}
I have managed to check is student already registered to course with this code:
Object.keys(registeredcoursesobject).forEach(function(key){
if( Object.keys(coursestoregisterobject).includes(key)) {
alert("You have already registered to "+key+" crn number course");
//return;
}
});
A course can be at most 2 days in a week and in 1 different time intervals(what if 2 time intervals??) which means that there will be only one "-" in days property and only one "*" in hours property.
I am new to programming and working on this for days any ideas ?
I hope this answer is still relevant for you. Here is what I have:
var registeredcoursesobject = {"00001":{"days":"Monday-Thursday","hours":"11:40-12:30*16:30-18:30"}}
var coursestoregisterobject = {"00002":{"days":"Monday-Friday","hours":"10:40-15:30*16:40-18:00"}}
var getTicks = function(timeStr) {
return new Date('1970-01-01T' + timeStr + ':00Z').getTime();
}
Object.keys(registeredcoursesobject).forEach(function(rKey){
if( Object.keys(coursestoregisterobject).includes(rKey)) {
alert("You have already registered to "+rKey+" crn number course");
return false;
};
Object.keys(coursestoregisterobject).forEach(function(cKey){
var regDays = registeredcoursesobject[rKey].days.split('-');
var regHours = registeredcoursesobject[rKey].hours.split('*');
var courseDays = coursestoregisterobject[cKey].days.split('-');
var courseHours = coursestoregisterobject[cKey].hours.split('*');
regDays.forEach(function(rDay, i) {
var rHourRange = regHours[i];
// I assume you need to check there is same date/time pain in registeredcoursesobject and coursestoregisterobject
courseDays.forEach(function(cDay, j) {
if (rDay == cDay) {
var cHourRange = courseHours[j];
// now, do you need to compare hours be equal exactly or do you need to check time overlap?
// assume you just need to ckeck hour ranges are equal, then:
if (rHourRange == cHourRange){
// means equal
alert("You have already registered to "+cKey+" crn number course on day "+cDay+" at "+cHourRange+" hours.");
return true;
}
// if you need to check range overlap
var rTime = rHourRange.split('-');
rTimeRange = [getTicks(rTime[0]), getTicks(rTime[1])];
rStartT = Math.min.apply(null, rTimeRange), rEndT = Math.max.apply(null, rTimeRange);
var cTime = cHourRange.split('-');
cTimeRange = [getTicks(cTime[0]), getTicks(cTime[1])]
cStartT = Math.min.apply(null, cTimeRange), cEndT = Math.max.apply(null, cTimeRange);
// now your rangeTime is a pair of int values, that represent time range rStartT:rEndT
// and your courseTime is a pair of int values cStartT:cEndT
// so now you just check the overlap of two integer pais.
// according to this: https://stackoverflow.com/questions/3269434/whats-the-most-efficient-way-to-test-two-integer-ranges-for-overlap#answer-3269471
if (rStartT < cEndT && cStartT < rEndT) {
alert("You have already registered to "+cKey+" crn number course on day "+cDay+" within time range "+cHourRange+" hours overlap with "+rHourRange+" time range.");
// means time ranges are overlap at some range. But I don't count the border, like "14:00-15:00" and "15:00-16:00" do not overlap
// otherwise replace < with <=
return true;
}
}
})
});
return false;
});
});
I am making some assumptions here about your task.
UPDATE: added time range check.
UPDATE: check keys equal first and values swap if start time is for some reason is bigger than end time.

script to validate birthdate

I got this script
$("#SocialSecurityNumber").attr("placeholder","YYYY-MM-DD-XXXX").blur(function () {
var str = $('#SocialSecurityNumber').val();
var res = /^([1-2]\d{3})\-([0-1][1-9])\-([0-3][0-9])\-([0-9]{4})$/.exec(str);
var todays_date = new Date();
var birth_date = new Date(res[1], res[2], res[3]);
if (todays_date - birth_date > 565633905872) {
$("#btn-activation").removeAttr('disabled');
$("#SocialSecurityNumber").removeClass("input-validation-error");
} else {
$("#SocialSecurityNumber").attr("placeholder","Please enter date of birth as YYYY-MM-DD-XXXX").addClass("input-validation-error");
$("#btn-activation").attr("disabled", "disabled");
}
});
});
Which will validate age, from input #SocialSecurityNumber
However, when entering letters or other jibberish it doesnt validate at all and i get js error
Uncaught TypeError: Cannot read property '1' of null
Could somone help me with how i can add so this script also validates incorrect characters? (when regex is not matched)
As per my comment, in javascript, if the RegEx does not match, then the result is null.
Therefore you are attempting to index a null variable... which is why you're seeing the error.
You need to check for a null value, with something like this...
var res = /^([1-2]\d{3})\-([0-1][1-9])\-([0-3][0-9])\-([0-9]{4})$/.exec(str);
var todays_date = new Date();
var birth_date = null;
if (res != null) {
birth_date = new Date(res[1], res[2], res[3]);
}
if (birth_date == null || todays_date - birth_date > 565633905872) {
...
You'll need to sort out the exact logic yourself, but hopefully this gives you an idea of what is going wrong.
If there is no match, then res will be null. So one thing which you can do is:
if(res.length==3)
var birth_date = new Date(res[1], res[2], res[3]);
This confirms that you get only right number of matches.

Categories

Resources