How can I find the min date in JavaScript? - javascript

How can I find the minimum date when the date format is dd-MM-yyyy like below. The output should return the min date from the dates below.
var a = "12-31-2018"
var b = "12-31-2019"

You can create Date objects using those two strings, compare them and return the older one.
function olderDate(dateA, dateB) {
var date1 = new Date(dateA);
var date2 = new Date(dateB);
if (date1 < date2)
return dateA;
else
return dateB;
}
console.log(olderDate("12/31/2018", "12/31/2019"));

We can try using Date.parse to convert the date strings into bona fide dates. Then, compare them:
var a = "12/31/2018";
var b = "12/31/2019";
var dateA = Date.parse(a);
var dateB = Date.parse(b);
var dateMin = dateA < dateB ? a : b;
console.log("minimum date is " + dateMin);

function olderDate(dateA, dateB) {
var date1 = new Date(dateA);
var date2 = new Date(dateB);
if (date1 < date2)
return dateA;
else
return dateB;
}
console.log(olderDate("12/31/2018", "12/31/2019"));

Related

How to compare javascript dates (strings) with a specific format

I have two dates in a specific format (strings). I need to verify if the current date is lower than the max allowed date:
var date_current = '03_25_2022';
var date_max = '03_30_2022';
The format will always be m_d_Y. Since these are technically strings, what would be the best way to compare them as dates?
I'm using this function but I'm not sure of the approach:
function compareDates(d1, d2){
var parts = d1.split('_');
var d1 = Number(parts[1] + parts[2] + parts[0]);
parts = d2.split('_');
var d2 = Number(parts[1] + parts[2] + parts[0]);
return d1 <= d2;
}
You can first convert these string into date object and then compare their timestamp as follow:
function strToDate(str) {
const splits = str.split('_');
if (splits.length !== 3) {
throw Error("Invalid date");
}
return new Date(splits[2], parseInt(splits[0]) - 1, splits[1]);
}
let dateCurrent = strToDate('03_25_2022');
let dateMax = strToDate('03_30_2022');
console.log(dateMax.getTime() > dateCurrent.getTime())

How to compare two timestamp values based on date ignoring time in js or moment js?

unixTimeStamp1 = 1532676600;
unixTimeStamp2 = 1532680500;
I have to compare the above two unix time stamp values and return true if both the dates are same.
Compare the toDateString of each date:
const getDateStr = secs => {
const d = new Date(secs * 1000);
return d.toDateString();
};
const d1 = getDateStr(1532676600);
const d2 = getDateStr(1532680500);
console.log(d1);
console.log(d2);
console.log(d1 === d2);
var unixTimeStamp1 = 1532676600;
var unixTimeStamp2 = 1532680500;
var date1 = new Date(unixTimeStamp1 * 1000);
var date2 = new Date(unixTimeStamp2 * 1000);
if ((date1.getFullYear() === date2.getFullYear()) &&
(date1.getMonth() === date2.getMonth()) &&
(date1.getDate() === date2.getDate())
) {
console.log("same");
}
You need to get the full date value from that timestamp using new Date().toDateString(). Then compare it. Also it is a unix timestamp so you need to convert that to JavaScript timestamp first using unixTimeStamp * 1000
var unixTimeStamp1 = 1532676600;
var unixTimeStamp2 = 1532680500;
function checkDate(unixTimeStamp1, unixTimeStamp2){
var date1 = new Date(unixTimeStamp1 * 1000).toDateString();
var date2 = new Date(unixTimeStamp2 * 1000).toDateString();
return date1 === date2;
}
console.log(checkDate(unixTimeStamp1, unixTimeStamp2));
unixTimeStamp1 = 1532156518;
unixTimeStamp2 = 1533839400;
console.log(checkDate(unixTimeStamp1, unixTimeStamp2));
But if you just want to get the date for the day ignoring the year and month then you can use getDate():
var unixTimeStamp1 = 1532676600;
var unixTimeStamp2 = 1532680500;
function checkDate(unixTimeStamp1, unixTimeStamp2){
var date1 = new Date(unixTimeStamp1 * 1000).getDate();
var date2 = new Date(unixTimeStamp2 * 1000).getDate();
return date1 === date2;
}
console.log(checkDate(unixTimeStamp1, unixTimeStamp2));
unixTimeStamp1 = 1532156518;
unixTimeStamp2 = 1533839400;
console.log(checkDate(unixTimeStamp1, unixTimeStamp2));

Parse String Time to JS Date Obj

I am trying to convert a string of time such as "7:30am" to JavaScript Date Object like Sat Nov 18 2017 7:30:00 GMT-0500 (EST)
My approach:
function dateObj(d) { // date parser ...
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') parts[0] = (+parts[0]) + 12;
date.setHours(+parts.shift());
date.setMinutes(+parts.shift());
return date
}
var startTime = "7:30";
var endTime = "9:30pm";
var startDate = dateObj(startTime); // get date objects
var endDate = dateObj(endTime);
console.log(startDate, endDate)
I got Invalid Date for both startDate, endDate.
Try here:
function dateObj(d) { // date parser ...
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') {
parts[0] = parts[0] + 12;
}
date.setHours(parts.shift());
date.setMinutes(parts.shift());
return date
}
var startTime = "7:30am";
var endTime = "9:30pm";
var now = new Date();
var startDate = dateObj(startTime); // get date objects
var endDate = dateObj(endTime);
var test = dateObj(startTime)
console.log(startDate, endDate)
I would rather use a regular expression to extract the date elements and also add some error handling for the case the date format is not valid.
And do not forget also to handle 12am and 12pm. This needs extra handling in the code.
See below:
function dateObj(d) { // date parser ...
const rx = /(\d{1,2})\:(\d{1,2})\s*(am|pm)/g;
const parts = rx.exec(d);
if (parts === null) {
return "Not a valid date: " + d;
}
date = new Date();
const amPm = parts.pop().toLowerCase();
const hour = parseInt(parts[1]);
if (amPm === 'pm') {
if (hour !== 12) {
parts[1] = (parseInt(parts[1])) + 12;
}
} else if (amPm === 'am' && hour === 12) {
parts[1] = 0;
}
date.setHours(parts[1]);
date.setMinutes(parts[2]);
return date
}
var startTime = "7:30";
var endTime = "9:30pm";
var startDate = dateObj(startTime); // get date objects
var endDate = dateObj(endTime);
console.log(startDate, endDate)
console.log(dateObj("7:30 pm"))
console.log(dateObj("7:30 am"))
console.log(dateObj("7:30am"))
console.log(dateObj("12:30pm"))
console.log(dateObj("12:30 am"))
This is working for me if you enter 9:30 pm instead of 9:30pm, the white space needs to be there for regex:
function dateObj(d) {
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') {
parts[0] = parts[0] + 12;
}
date.setHours(parts[0]);
date.setMinutes(parts[1]);
return date;
}
It just needs a space before am/pm :
d = t => new Date(new Date().toDateString() + t.replace(/(.*\d)/, " $1 "))
console.log(d("7:30").toString())
console.log(d("7:30am").toString())
console.log(d("9:30pm").toString())
This will create a new Date object that includes the current time.
But it is based on the timezone of where the code is run.
var timeRe = /(\d+):(\d+)([amp]*)/gi;
function timeParse(time) {
var today = new Date();
var match = time.split(timeRe);
console.log(time, match);
if (match) {
var hours = parseInt(match[1],10)+(match[3].toLowerCase()==='pm'?12:0)%24;
today.setHours(hours);
today.setMinutes(parseInt(match[2],10));
today.setSeconds(0);
}
return today;
}
var startTime = "7:30";
var endTime = "9:30pm";
var startDate = timeParse(startTime); // get date objects
var endDate = timeParse(endTime);
console.log(startDate, endDate)

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 get the holidays date in my case?

I am trying to get the holidays of given range of dates.
For example:
var holiday = ['2014-01-01','2014-07-04','2014-12-24', '2014-12-25'...other holidays elements ];
var startDate = '2014-08-01'
var endDate = '2014-12-30';
var holidays=getHolidays(startDate, endDate);
//console.log(holidays) -> output 2014-12-24 and 2014-12-25.
getHolidays = function(startDate, endDate) {
var holidays=[];
//not sure how to get holidays here....
return holidays
}
I was hoping to write a function to get 2014-12-24 and 2014-12-25. My brain is fried now and I don't know what's the best approach on this. Can anyone help me about it? Thanks a lot!
The solution is to use filter function of array. The first parameter is the array you need to filter, and in your case, it's ['2014-01-01', '2014-07-04', '2014-12-24', '2014-12-25'].
var getHolidays = function(holiday,startDate, endDate) {
return holiday.filter(function(element){
var start = new Date(startDate);
var end = new Date(endDate);
var temp = new Date(element);
return temp >= start && temp <= end;
});
}
var holiday = ['2014-01-01', '2014-07-04', '2014-12-24', '2014-12-25'];
var startDate = '2014-08-01'
var endDate = '2014-12-30';
var holidays = getHolidays(holiday,startDate, endDate); //["2014-12-24", "2014-12-25"]
It works exactly as what you expect as shown in
JSFiddle
You could try turning them into date objects, and then comparing them that way. Something like:
var holidays = ['2014-01-01','2014-07-04','2014-12-24', '2014-12-25'];
var startDate = '2014-08-01';
var endDate = '2014-12-30';
var getHolidays = function(startDate, endDate) {
var startTime = new Date(startDate).getTime();
var endTime = new Date(endDate).getTime();
var output = [];
holidays.forEach(function(holiday) {
var holidayTime = new Date(holiday).getTime();
if (holidayTime >= startTime && holidayTime <= endTime) {
output.push(holiday);
}
});
return output;
}
var holidays = getHolidays(startDate, endDate);
console.log(holidays);
As plain strings, the getHolidays function can be:
// Get holidays between two dates
function getHolidays(startDate, endDate) {
var output = [];
var i = 0;
var holiday;
while ((holiday = holidays[i++]) && holiday < endDate) {
if (startDate <= holiday) {
output.push(holiday)
}
}
return output;
}
If you are using ISO 8601 date strings, there's no need to convert them to Date objects. One of the reasons for the ISO format is that in most systems, you can compare strings directly rather than Date objects or some number value.
You can also parse the strings to Date objects, then use those to do the calculations but it takes more code for no real benefit:
// Parse date string in y-m-d format
function parseYMD(s) {
var b = s.split(/\D/);
var d = new Date();
d.setHours(0,0,0,0);
d.setFullYear(b[0], --b[1], b[2]);
return d.getFullYear() == b[0] && d.getDate() == b[2]? d : NaN;
}
// Holiday array
var holidays = ['2014-01-01','2014-07-04','2014-12-24', '2014-12-25'];
// Get holidays between two dates
function getHolidays(startDate, endDate) {
startDate = parseYMD(startDate);
endDate = parseYMD(endDate);
var output = [];
var i = 0;
var holiday;
for (var i=0, iLen=holidays.length; i<iLen; i++) {
holiday = parseYMD(holidays[i]);
if (holiday <= endDate) {
if (holiday >= startDate) {
output.push(holidays[i]);
}
}
}
return output;
}
console.log(getHolidays('2014-08-01', '2014-12-30')); // ["2014-12-24", "2014-12-25"]

Categories