find max date out of three datetime variables - javascript

I have question regarding date comparison in javascript.
I want to find max date out of three datetime variables.
Like, i can find max date in c# linq using following short way
maxDate= new[] {p1.Date, p2.Date, p3.Date}.Max();
Does javascript has such nice way to do that?

You can just use Math.max, like this:
var d1 = new Date();
var d2 = new Date();
var d3 = new Date();
var max = Math.max(d1, d2, d3);
// Will give you the max Date
console.log(new Date(max));

You can use sort method of js array to find min & max date
/* In ascending order*/
function sortDates(a, b)
{
return a.getTime() - b.getTime();
}
/* in descending order.max & min value will be different
function sortDates(a, b)
{
return b.getTime() - b.getTime();
} */
var dates = [];
dates.push(new Date("03/18/2016"))
dates.push(new Date("03/18/2015"))
dates.push(new Date("03/18/2017"))
dates.push(new Date("03/18/2018"))
var sortedArray = dates.sort(sortDates);
var minDate = sortedArray [0];
var maxDate = sortedArray [sortedArray .length-1];
console.log(minDate , maxDate);
jsfiddle

Related

Array of days in between months

I have two dates: Startdate and enddate
startdate = "10/10/2018" enddate = "03/09/2019"
I am trying to create an array of dates between those 2 dates. I have the following code.
function getDateArray (start, end) {
var arr = [];
var startDate = new Date(start);
var endDate = new Date(end);
endDate.setMonth( endDate.getMonth());
while (startDate <= endDate) {
arr.push(new Date(startDate));
startDate.setMonth(startDate.getMonth() + 1);
}
return arr;
}
Then calculate the number of days between those months in between.
10/10/2018 to 11/10/2018 = 30 days
11/10/2019 to 12/10/2018 = 30 days or so depending on number of days between the 2 dates and then create an array of the dates.
[30,30,31....till end date]
function daysBetween(date1, date2 )
{
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var dayDifference = Math.ceil(timeDiff / (1000 * 3600 * 24));
return dayDifference;
}
I tried the following code and it's returning the array of number of dates however, it's not accurate. It keeps returning 32 days in October. The output it's giving right now is as follows. I am not sure what i am doing wrong here but it looks like it's only going till February and displaying the result.
Any help will be appreciated. Thank you.
Output: [32,30,31,31,28]
var dateArr = getDateArray(z, y);
console.log(dateArr);
var dayCounts = "";
for (var x = 0; x < dateArr.length-1; x++)
{
dayCounts += daysBetween(dateArr[x], dateArr[x+1]);
}
console.log("datearrlength" + dateArr.length);
console.log(dayCounts);
i think this will work for you,
Date.prototype.addDay= function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function getDateBwStartandEnd(sdate, edate) {
var dateArray = new Array();
var currentDate = sdate;
while (currentDate <= edate) {
dateArray.push(new Date (currentDate));
currentDate = currentDate.addDay(1);
}
return dateArray;
}
** Shamelessly copied from web, but this works fine for me.
While the following doesn't answer your question it is an alternative approach to the overall problem you are attempting to solve.
One approach would be to simply get the time difference between the two dates and then divide by the number of microseconds in a day. As you will notice though it is not exact and so a floor is used to get the days. There are other concerns with this approach as well such as date ranges before the epoch but it is a very simplistic approach and might work depending on your needs.
const startDate = '10/10/2018';
const endDate = '03/09/2019';
const start = (new Date(startDate)).valueOf();
const end = (new Date(endDate)).valueOf();
const timeBetween = end - start;
console.log({timeBetween, days: Math.floor(timeBetween/86400000)});
A slightly more robust is to essentially use a counter that increments itself by adding 1 day to the counter and the start date while the start date is less than the end date. Again, there are some concerns with this approach but that also depends on your needs.
const startDate = '10/10/2018';
const endDate = '03/09/2019';
let start = new Date(startDate);
const end = (new Date(endDate)).valueOf();
let daysBetween = 0;
while (start.valueOf() < end) {
daysBetween++;
start.setDate(start.getDate() + 1);
}
console.log(daysBetween);
Finally, a more robust solution to avoid the variety of issues with manipulating and working with dates is to use a library like momentjs. Using its difference method would look like the following.
const start = moment([2018, 10, 10]);
const end = moment([2019, 3, 9]);
console.log(end.diff(start, 'days'));
<script src="http://momentjs.com/downloads/moment.min.js"></script>
Using the following code worked for me. I added 1 extra month to my end date and it gives the proper date range. Also, instead of Math.ceil, i used Math.round and it gives the right number of date.
function getDateArray (start, end) {
var arr = [];
var startDate = new Date(start);
var endDate = new Date(end);
endDate.setMonth( endDate.getMonth());
while (startDate <= endDate) {
arr.push(new Date(startDate));
startDate.setMonth(startDate.getMonth() + 1);
}
return arr;
}

Get days using two dates in js

I'm having this trouble where I can only get the days between specified 2 dates. Please see the code below:
var getDaysArray = function(start, end) {
for (var arr = [], dt = start; dt <= end; dt.setDate(dt.getDate() + 1)) {
arr.push(new Date(dt));
}
return arr;
};
var daylist = getDaysArray(new Date('08/13/2018'), new Date('08/17/2018'));
daylist.map((v) => v.toISOString().slice(0, 10)).join("");
console.log(daylist);
The output of the code above is:
Expected output (due to start and end dates 08/13/2018 and 08/17/2018):
0: Date 2018-08-13T16:00:00.000Z
1: Date 2018-08-14T16:00:00.000Z
2: Date 2018-08-15T16:00:00.000Z
3: Date 2018-08-16T16:00:00.000Z
4: Date 2018-08-17T16:00:00.000Z
Note: The code above was from one of the SO answers found somewhere.
toISOString represents the date in UTC format. You are probably in positive timezone offset, that's why the UTC representation of your date objects are a day off. You can use toLocaleString instead to represent your dates in your timezone.
Another issue is that Array.prototype.map retuns a new array, which you forgot to assign to daylist Without that assignment, no changes in daylist will be made.
Below snippet works as per your requirements.
var getDaysArray = function(start, end) {
for (var arr = [], dt = start; dt <= end; dt.setDate(dt.getDate() + 1)) {
arr.push(new Date(dt));
}
return arr;
};
var daylist = getDaysArray(new Date('08/13/2018'), new Date('08/17/2018'));
daylist = daylist.map((v) => v.toLocaleString());
console.log(daylist);

Finding max of dates

I have some dates in some different format.
date1 = 2015-05-27T04:51:12.715Z
date2 = 2015-05-27T04:51:12.782Z
date3 = 2015-05-27T04:51:12.865Z
Dont know what this format means specially the last 4 characters.And how would I find the maximum of these dates in Javascript
Just sort the array and get the first item
var date1 = '2015-05-27T04:51:12.715Z';
var date2 = '2015-05-27T04:51:12.782Z';
var date3 = '2015-05-27T04:51:12.865Z';
var array = [date1, date2, date3];
array.sort(function(a,b) {
return new Date(a) < new Date(b);
});
var max = array[0];

How to check if any date from array is in date range?

Hope you are all well.
I need to check if any date from array
var arrayDates = ["2013-07-26", "2013-07-27"];
is in date range of
var startDate = new Date("2013-07-10");
var endDate = new Date("2013-07-10");
I am really stuck and started to confuse myself. Can anyone help me with that please.
P.S. Dates above are for example, they will be dynamic.
Thank you!
You will need to use real date objects rather than strings.
maybe have a look at using dateJs for parsing dates
http://www.datejs.com/
But really you need to iterate through the array of dates and check if they fall between the tick value of your start and end dates.
Try this:
var arrayDates = [];
arrayDates.push(new Date(2013, 7 , 26));
arrayDates.push(new Date(2013, 7 , 27));
var startDate = new Date("2013-07-10");
var endDate = new Date("2013-07-10");
for(i = 0; i < arrayDates.length; i++){
if(arrayDates[i] >= startDate && arrayDates[i] <= endDate) {
alert('Yes');
}
}
Another method - http://jsfiddle.net/Mh5vn/
var ds = ["2013-07-26", "2013-07-27"];
Array.prototype.between = function(arg) {
var d1 = new Date(this[0]),
d2 = new Date(this[1]),
d3 = new Date(arg);
return (d1.getTime() <= d3.getTime() && d3.getTime() <= d2.getTime());
}
console.log( ds.between('2013-07-26') );
// true
console.log( ds.between('2013-07-28') );
// false
After you have the date objects you can compare them in a pretty straight forward way. See this link at the bottom.
I see your question is tagged jquery, so you could do something like this:
$.each(arrayDates, function(i, val) {
if (val > endDate || val < startDate)
{
//Date is outside of that range
}
});
Hopefully you can convert these dates to numbers and compare them, here an example :
var arrayDates = ["2013-07-26", "2013-07-27"];
var unDash = function (string) {
return string.replace(/-/g, "")
}
var dateInRange = function (date, startDate, endDate) {
date = unDash(date)
startDate = unDash(startDate)
endDate = unDash(endDate)
return date > startDate && date < endDate
}
// You now filter your array to retrieve your dates
var dates = arrayDates.filter(function (date) {
return dateInRange(date, '2013-07-10', '2013-07-31')
})

Calculate difference between two calendar dates in javascript

I need to calculate difference between two calendar dates. I have gone through various posts but the value returned is not correct.
Heres' my code:-
function getTotalDays()
{
var date11 = document.getElementById("departure_date").value;
var date22 = document.getElementById("arrival_date").value;
var one_day=1000*60*60*24;
var date1 = new Date(date11);
var date2 = new Date(date22);
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
// Convert back to days and return
var diffDays = Math.round(difference_ms/one_day);
alert(diffDays);
}
suppse the difference is 2 days its showing as 59.
What's wrong..??
The values you are passing to the date object are likely wrong. Its probably easier for you to do something like this:
var date1 = getDate(date11);
var date2 = getDate(date22);
with getDate being:
function getDate(date) {
//date format dd/mm/yyyy
var dateArr = date.split('/');
var date = new Date(dateArr[2], dateArr[1], dateArr[0]);
return date;
}

Categories