How to check in AngularJs if some dates are greater then others - javascript

I need to check if some date fields are greater then others.
I solved in this way for only one couple of dates. I can't find a solution for multiples couples of variables like these:
$scope.date1startFrom;
$scope.date1startTo;
$scope.date2startFrom;
$scope.date2startTo;
$scope.date3startFrom;
$scope.date3startTo;
I have to see the alert only if very element of the couple has a value. I find this solution but I want to extend it to multiple values but I can't.
var datesAreDefined = $scope.date1startFrom && $scope.date1startTo;
if (datesAreDefined && !periodFromAndToIsValid($scope.date1startFrom, $scope.date1startTo)) {
alert("error");
}
function periodFromAndToIsValid (from, to){
var fromDate = new Date(from).getTime();
var toDate = new Date(to).getTime();
return toDate >= fromDate;
}

I would recomend to use something like MomentJS its very effective for this case:
https://momentjs.com/
In this link you can find the way to make comparisons easily between dates.
https://momentjs.com/docs/#/query/

Related

Get the length between two dates in hours

I am reading sleep data into my react-native app using react-native-healthkit, and I need to find a way to get the total amount of sleep time. The data is read in like this:
If anyone has any ideas on the best way to handle this data, please let me know.
extension Date {
/// Hours since current date to given date
/// - Parameter date: the date
func hours(since date: Date) -> Int {
let calendar = Calendar.current
let dateComponents = calendar.dateComponents([.hour], from: self, to: date)
return dateComponents.month ?? 0
}
}
date2.hours(since: date1)
Using .timeIntervalSince is a bad practice, because some hours may be shorter than other.
If anyone has any ideas on the best way to handle this data please let me know.
It really depends on how you're parsing that JSON data. I won't cover JSON parsing here because there are many, many tutorials and blog posts on that topic. Here's one in case you're not sure where to start.
Your goal is to end up with date objects (Date in Swift, NSDate in Objective-C). For example, if you have the values as strings, you can use DateFormatter to parse the strings into Date objects.
Once you have those date objects you can use the operations that those objects supply to get a TimeInterval, which is a double representing an interval in seconds. Convert that to hours by dividing by 3600:
let interval = endDate.timeIntervalSince(startDate)
let hours = interval / 3600
Try this
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
guard let startDate = dateFormatter.date(from: "yourStartDate"),
let endDate = dateFormatter.date(from: "yourEndDate") else {
return
}
let difference = endDate.timeIntervalSince(startDate)
If you are targeting iOS 13 and above you can use
endDate.hours(since: startDate)
instead of timeInterval

Calculate a couple of business days before a date

I have to calculate X working days before a date in javascript. I have an array of holidays, how can I do this?
I can make a while loop with my date and change it to the previous day and check if it's a business day then increment my variable but is it a good way to do this?
In normal languages you could easily solve this with a hashset. It has vary fast look up times, and random access.
However, Javascript isn't like all the other children. So it has it's own special way of doing this. The easiest way is just an object.
var holidays = {
1:true,
7:true,
18:true
}
I use days since newyear, but there isn't anything wrong with using a date or something else.
Then you can make a little helper function:
var checkDate = function(value){
return holidays [value] === true;
};
Then you just do checkDate(dayOfYear) and it will return true or false if it's a holiday. Then you can easily do
//This is more pseudocode than javascript, since I haven't done javascript in years
while checkDate(--dayOfYear === true)
previousBussinesDay = dayOfYear;
Or something similar to find the actual day.

Javascript prototype function: decimal time value to a time string

On a project I'm currently working on in JavaScript, I'm using decimal formats so it's easier to calculate with rather than using an hour/minute format in strings (calendar related project). To display the time on the user's screen though, the timecode has to be shown as hh:mm.
I thought it would be great to use a String prototype function for this as it would allow me to use code like:
var time = 8.75;
document.write("Meeting at "+time.toTime()); // writes: Meeting at 8:45
So far, I've got that almost working, using:
String.prototype.toTime = function(){
var hrs = this.toString().slice(0,this.indexOf("."));
var min = Math.round(this.toString().slice(this.indexOf("."))/100*60);
min = min<10 ? "0"+min : min.toString();
return hrs+":"+min;
}
The problem, though, is that this will only work if the variable time is a string. Otherwise it will give an undefined error.
Would there be any way of applying the prototype to a different object in JavaScript, so that I don't have to use time.toString().toTime()?
Thanks!
Firstly, you can add to the Number prototype. Many people will warn against modifying prototypes, which in many cases is justified. If there is a chance 3rd party scripts will be running alongside yours, it is a danger to modify prototypes.
Secondly, I simplified your code a little, using modulus, and floor to calculate the hrs and mins...
Number.prototype.toTime = function(){
var hrs = Math.floor(this)
var min = Math.round(this%1*60)
min = min<10 ? "0"+min : min.toString();
return hrs+":"+min;
}
var time = 8.25;
console.log("Meeting at "+time.toTime());
You can use Object.prototype.toTime.

JavaScript - Compare two timestamps

i try to compare two timestamps like this:
var nowDate = new Date();
var givenDate = new Date(parseInt(year), parseInt(month), parseInt(day), parseInt(hour), parseInt(minute), 0);
var nd_timestamp = nowDate.getTime();
var gd_timestamp = givenDate.getTime();
if (nd_timestamp > gd_timestamp) {
alert("yes");
}
But it is not working properly. If i look at the nd_timestamp and gd_timestamp everything looks fine, but the if-clause is not working. If i remove the parseInt(year)... and enter Date(2012, 04, 20, 0, 0, 0) the if-clause is working.
The variables year, month etc. comes through a function, but if i debug it with alert(year) etc. everything is fine. The given date through the form is smaller than the actual date.
Does anybody know why it is not working with variables?
Thanks!
You should check the values you pass to the Date constructor for validity, which includes explicitly specifying 10 as the second parameter to all of your parseInt calls to avoid nasty surprises.
Regarding the second parameter, the documentation says
While this parameter is optional, always specify it to eliminate
reader confusion and to guarantee predictable behavior. Different
implementations produce different results when a radix is not
specified.
You have to take 1 from Month because for some reason it is zero based, unlike the others.

Using a funcCall that retrieves multiple fields

Ello, I'm using jQuery-Validation-Engine and i don't know if this is currently possible but, Is there a way for you to possibly use the funcCall in a senario such as this.
I have to check a date range using 2 textboxes. I want to bind funcCall[dateRangeCheck] in such a way that I can get access
to 2 fields as opposed to just the one. The end result would would something like this.
dateRangeCheck = function (fields, rules, i, options) {
if (isDate(fields[0]) && isDate(fields[1])) {
if (!dateCompare(fields[0], fields[1])) {
return "* Invalid Date Range";
}
}
};
Or possibly all the fields that a utilizing this particular funcCall like this
dateRangeCheck = function (fields, rules, i, options) {
for (var i=0;i<fields.length;i++)
if(!isDate(fields[i]){
return "* Invalid Date Range";
}
}
};
Is there some way to accomplish this?
Well now jQuery-validation-engine does support date range checking. Just made the commit myself waiting for it to be reviewed. lol, But no to that second example as of now.
Here is the source. Have a nice day.
Update
The latest version does support group validation.

Categories

Resources