Check Date range in Javascript and angular js - javascript

I have to check the given date which is dd/MM/yyyy format that it should fall within 90 days range in java script?

Take the difference between two dates and divide it by the number of milliseconds in a day.
var difference = (new Date().getTime() - startDate.getTime())/(1000*60*60*24.0)
Find out if the difference between the two dates is more than 90 days
alert Math.abs(difference) < 90 ? "Valid Time" : "Invalid Date Range"
Full working example:
var startDate = new Date('2015-01-01 00:00:00');
var difference = (new Date().getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24.0);
alert(Math.abs(difference) < 90 ? "Valid Time" : "Invalid Date Range");

Related

JavaScript: is there a way to detect that a given date in such a format is within last X days?

I have a bunch of timestamp formatted like this
const dates = ['2021.6.01', '2021.6.11', '2021.9.02']
I wanted to write a util that can tell me if a date with such a format is within the last X days of another date.
For example, 2021.6.10 is within the last 7 days of 2021.6.12 while 2021.6.01 is not within the last 7 days of 2021.6.12.
I was think the API interface would be but please feel free to suggest a better naming
function isWithinTheLastDays(originalDate, date, days)
I found it really tricky to implement by hand and there are a lot of edge cases.
Parse the dates with the Date constructor, subtract the two dates and convert the millisecond difference to days (by dividing by 86400000), then check whether it is smaller or equal to days:
function isWithinTheLastDays(originalDate, date, days){
return (new Date(date) - new Date(originalDate)) / 86400000 <= days;
}
console.log(isWithinTheLastDays('2021.6.10', '2021.6.12', 7)) //2 day diff
console.log(isWithinTheLastDays('2021.6.10', '2021.6.17', 7)) //7 day diff
console.log(isWithinTheLastDays('2021.6.10', '2021.6.18', 7)) //8 day diff
turning it to Unix timestamp and subtracting it
function isWithinTheLastDays(originalDate, date, days){
if(Math.abs(
new Date(date).getTime()/1000
- new Date(originalDate).getTime()/1000
)/60/60/24 >= days){
return true;
}else{
return false;
};
}
You can try this:
Note: this will return true if the dates is X days after and before the date you've set
const dates = ['2021.08.26', '2021.6.11', '2021.9.02']
function isWithinDays({ originalDate, date, range }) {
return parseInt(((new Date(date) - new Date(originalDate)) / (1000 * 60 * 60 * 24)), 10) <= range && parseInt(((new Date(date) - new Date(originalDate)) / (1000 * 60 * 60 * 24)), 10) >= 0 ? true : false
}
for (var i = 0; i < dates.length; i++) {
console.log(isWithinDays({
originalDate: dates[i],
date: new Date('2021-08-27'),
range: 10
}))
}

Javascript Subtract Set Date by Todays Date Within Array

currently I have an array that is pulling a future date, and I'm trying to do the "future date" - "todays date" within an array to get a number. The format that the future date is currently being outputted as is below.
2021-06-21T16:23:26.182Z
I was wondering how I could trim the date when it's being pulled within an array, and then subtract the future date from todays date, to give a number output.
Currently within the array the future date property is being pulled as shown below.
futureDate: machine.future.date
Would I just do the "split" function on the date to trim it down to 2021-06-21? Any help would be much appreciated, thanks!
var futuredate="2021-06-21T16:23:26.182Z";
var dif = new Date(futuredate).setHours(0,0,0,0) - new Date().setHours(0,0,0,0);
// dif is in milliseconds
// days difference = dif / 1000 / 60 / 60 / 24
// years difference = dif / 1000 / 60 / 60 / 24 / 365
To address your comment, you can map one array to another - getting the diff value along the way, like:
var arr = ["2021-06-21T16:23:26.182Z", "2021-06-22T16:23:26.182Z"];
var difarr = arr.map(futuredate => {
return (new Date(futuredate).setHours(0,0,0,0) - new Date().setHours(0,0,0,0)) / 1000 / 60 / 60 / 24 ;
})
//difarr is an array of the difference in days (in this example)

JavaScript, how to create difference of date with moment.js

I am having a problem with creating an error message on a page where there is a "from date:", and a "to date:". If the difference between the two dates is greater than or equal to 60 days, I have to put up an error message.
I am trying to use moment.js and this is what my code is looking like now. It was recommended that I use it in knockout validation code. this is what it looks like right now:
var greaterThan60 = (moment().subtract('days', 60) === true) ? "The max range for from/to date is 60 days." : null;
I am still not sure how to make it greater than 60 days, not just equal to 60 days. This is what my boss gave me to help.
Reference site for moment().subtract
moment.js provides a diff() method to find difference between dates. please check below example.
var fromDate = 20180606;
var toDate = 20180406;
var dif = moment(fromDate, 'YYYYMMDD').diff(moment(toDate, 'YYYYMMDD'),'days')
console.log(dif) // 61
subtract returns a new moment object. So checking for true always returns false. You can use range and diff to calculate a diff in days and check that:
let start = moment('2016-02-27');
let end = moment('2016-03-02');
let range = moment.range(start, end);
let days = range.diff('days');
let error = null;
if (days > 60) {
error = "The max range for from/to date is 60 days.";
}
You Can try this.
var date = Date.parse("2018-04-04 00:00:00");
var selectedFromDate = new Date(date);
var todayDate = new Date();
var timedifference = Math.abs(todayDate.getTime() - selectedFromDate.getTime());
var daysDifference = Math.ceil(timedifference/(1000 * 3600 * 24));
just use if else loop for greater than 60 days validation.
if(daysDifference > 60)
{
alert("From Date should be less than 2 months");
}
Use the .isSameOrAfter function to compare if the end value is greater than or equal to the start value plus sixty days. Example:
var greaterThan60 = toDate.isSameOrAfter(startDate.add(60, 'days'));
where toDate is your end time as a moment object and startDate is the start time as a moment object. If the end date is greater than or equal to 60 days after the start date, greaterThan60 will be true.
References:
isSameOrAfter
add

Javascript: Calculate time difference between 2 days with conversion to UTC

I have a start and end dates, I need to convert them to UTC and calculate how many days are in between (including).
So for example:
(01/08/15 10:00 GMT+3) - (04/08/15 10:00 GMT+3) will return 4
(01/08/15 00:00 GMT+3) - (04/08/15 10:00 GMT+3) will return 5
The following code works for those dates like the first case, but not for the second (where after the conversion there is an additional day):
var startDateInUTC = new Date(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate(), start.getUTCHours(), start.getUTCMinutes(), start.getUTCSeconds());
var endDateInUTC = new Date(end.getUTCFullYear(), end.getUTCMonth(), end.getUTCDate(), end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds());
var totalDays = Math.floor((endDateInUTC - startDateInUTC) / (1000 * 60 * 60 * 24)) + 1;
I tried changing the Math.floor to Math.round but that just adds me a day in some scenarios.
What am I doing wrong?
function calculate(start, end)
{
var startDateInUTC = new Date(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate(), start.getUTCHours(), start.getUTCMinutes(), start.getUTCSeconds());
var endDateInUTC = new Date(end.getUTCFullYear(), end.getUTCMonth(), end.getUTCDate(), end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds());
return Math.floor(millisecondsToDays = (Date.parse(endDateInUTC) - Date.parse(startDateInUTC)) / 1000 / 3600 / 24);
}
console.log(calculate(new Date("2015/08/01 10:00:00"), new Date("2015/08/04 10:00:00")));
console.log(calculate(new Date("2015/08/01 00:00:00"), new Date("2015/08/04 10:00:00")));
//the answer in both cases will be 3
Use Date.parse here. It will convert the dates into timeStamps. you can subtract these and then calculate the amount back to days. Use Math.floor to round down, since 6.25 is 6 days and 6 hours.
timeStamps are the amount of milliseconds that have passed since 1970/01/01 00:00:00. That date is always UTC. When you have two timestamps you can calculate the difference between them. Date.parse() returns the timestamp on a valid date. new Date(timestamp) will return the date based upon the timestamp.
To get date barriers you can do an extra calculation:
(start time + 24 * days + end time) / 24
Round this figure down and you get the day barriers.
Example:
21 + 24 * 3 + 7 = 100
103 / 24 = 4.1666666.....
Math.floor(4.166666) = 4;
I ended up gathering a pretty simple solution combining some bits of Mouser's answer (Thanks!)
function calcStreamDaysInUTC(start, end) {
try {
// Translate to UTC
var startDateInUTC = new Date(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate(), start.getUTCHours(), start.getUTCMinutes(), start.getUTCSeconds());
var endDateInUTC = new Date(end.getUTCFullYear(), end.getUTCMonth(), end.getUTCDate(), end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds());
// Reset everything but the date
startDateInUTC.setHours(0);
startDateInUTC.setMinutes(0);
startDateInUTC.setSeconds(0);
endDateInUTC.setHours(0);
endDateInUTC.setMinutes(0);
endDateInUTC.setSeconds(0);
var totalDays = (endDateInUTC - startDateInUTC) / (1000 * 60 * 60 * 24) + 1;
return totalDays;
} catch (e) {
return -1;
}
}

JavaScript: check if date A is at most 3 times earlier/late than date B

I have to write a JavaScript function that checks if two dates (formatted dd/MM/yyyy) make a time interval of at most 3 months.
I can retrieve the two values from two textboxes (no need to check formatting, I have been given a calendar control that automatically formats the date correctly).
I have almost no experience with JavaScript. Can you help me?
Examples:
15/2/2011, 13/2/2011 -> return true
6/1/2011, 5/10/2010 -> return false
I already check that date A is later than date B (the calendar does it for me)
No need for a ton of code:
function days_between(date1, date2) {
return Math.round(Math.abs(date1 - date2) / (1000 * 60 * 60 * 24)) > 90;
}
date1 and date2 are Date objects e.g.
var date1 = new Date('mm/dd/yyyy');
You can find difference between two dates and return value accordingly.
function days_between(date1, date2) {
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
// Convert both dates to milliseconds
var date1_ms = date1.getTime()
var date2_ms = date2.getTime()
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)
// check converting back to days and return
return (Math.round(difference_ms/ONE_DAY) >90);
}
If you are unable to check or parse date correctly then you should use
var x=txtDate1.split("/"); //Here txtDate1 and txtDate2 are values from your textbox
var y=txtDate2.split("/");
//date format(Fullyear,month,date)
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0])

Categories

Resources