date-fns check if date exist in array - javascript

I'm using date-fns, I can use helpers like isMonday(day) that returns true is if the day is a Monday, or isWithinRange(start, end) to check if a date is within a range, however, is there a way to return true if a date is in an array of dates?

To easy, just use Array prototype.some
const dateInArray = (date, array) => array.some(d => +d === +date);

Related

Date parsing from different formats?

I have a string, which can come in different formats:
01.01.2020
01/01/2020
01-01-2020
or
2020-01-01
2020.01.01
2020/01/01
Now if I try doing
const date = new Date(myDateString);
I will in some cases get an error "Invalid Date".
How can I cover all scenarios and transform any scenario into a valid date?
It seems like the new Date(), only takes the format Y-m-y?, even though the other cases are also "valid" dates?
You can moment to do that. But you need to know which format is used.
https://stackoverflow.com/a/44134515/3573340
Date() constructor is accurate if it's parameters are YYYY, MM, DD. The dates of Jan 1, 2020 should go like this:
new Date(2020, 0, 1) // Month is 0 index, so MM -1
Given an array of strings .map() and split() each by .-/ delimitters, resulting in sub-arrays of 3 strings from each string:
strArr.map(str => str.split(/[-./]/))
then .flatMap() to catch any array that starts with 2 digits and .reverse() it:
.flatMap(sub => sub[0].length === 2 ? [sub.reverse()] : [sub])
Finally, .flatMap() each sub-array into the Date() constructor:
.flatMap(sub => [new Date(+sub[0], +sub[1] - 1, +sub[2])])
const jan1_2020 = [
`01.01.2020`,
`01/01/2020`,
`01-01-2020`,
`2020-01-01`,
`2020.01.01`,
`2020/01/01`
];
const formatDate = strArr => strArr.map(str => str.split(/[-./]/)).flatMap(sub => sub[0].length === 2 ? [sub.reverse()] : [sub]).flatMap(sub => [new Date(+sub[0], +sub[1] - 1, +sub[2])]);
let x = formatDate(jan1_2020);
console.log(x);
You can split the string on the known delimiters and then see whether the first part has four digits. If so, you know it's year-month-day. If not, you know it's month-day-year. You can then construct the date accordingly:
const dateStrings = [
"10.31.2020",
"10/31/2020",
"10-31-2020",
"2020-10-31",
"2020.10.31",
"2020/10/31",
]
function parseDateStr(str) {
// split on dots, dashes, and slashes
const parts = str.split(/[./-]/);
// mm-dd-yyyy
const [year, month, day] = parts[0].length > 2 ? parts : [parts[2], parts[0], parts[1]];
// alternate for dd-mm-yyyy
// const [year, month, day] = parts[0].length > 2 ? parts : parts.reverse();
// construct and return the date. (month is 0 based)
return new Date(year, month - 1, day);
}
const results = dateStrings.map(parseDateStr);
console.log(results);
JavaScript will parse the dates in following formats:
ISO Date - YYYY-MM-DD
Short Date - YYYY/MM/DD
Long Date - Jan 01 2022
Some other versions of the dates also might also work but the best practice is to limiting your formats to ISO format. For more on js date formats refer this

How to sort by next available date?

I have an array of objects with a date format that looks this way:
"offline_available": "5/1/2021"
As I understand it is the date formatted by the toLocaleDateString() method.
How can I sort all objects by next available date?
You need to translate your date string into a date object in the comparison function.
yourArray.sort( (a,b) => new Date(a.offline_available) - new Date(b.offline_available))
Start with this - assuming the date is mm/dd/yyyy
const arr = [
{"offline_available": "5/1/2021"},
{"offline_available": "12/13/2020"},
{"offline_available": "5/3/2020"},
{"offline_available": "5/3/2021"}
]
const sorted = arr.slice(0).sort((a,b) => new Date(a.offline_available) - new Date(b.offline_available))
console.log(sorted)
What is "sort by next available date"?

Compare Dates in Array of MongoDB Object with different formats

I am using a datepicker in my frontend which sends a date using an AJAX Request.
Now this date is in the format - 'YYYY-MM-DD'. I have an array of dates which I have to compare this date with and pick out which are equal. This array is from a Mongo DB collection where I have TimeZone included in the field as well, for example - "2020-06-03T00:00:00.000Z"
My Slot Json Object
{
date: [
2020-06-03T00:00:00.000Z,
2020-06-05T00:00:00.000Z,
2020-06-07T00:00:00.000Z
],
__v: 0
}
I have to loop over each date in the date array and compare it with the date I get from frontend.
Let's say user input date is
let userInput = '2020-06-03';
And now I have to compare it with the date array
How do I ensure that the following comparision leads me to get a true value for
'2020-06-03' and '2020-06-03T00:00:00.000Z'
I am looking at a solution which is appropriate when looping over all these array elements.
assuming, that your date array always is at 00:00:00 o'clock, i'd suggest something like this:
const dates = [
'2020-06-03T00:00:00.000Z',
'2020-06-05T00:00:00.000Z',
'2020-06-07T00:00:00.000Z'
];
let userInput = '2020-06-03';
function findDates(date) {
const searchDate = Date.parse(date);
const foundDates = [];
dates.forEach(date => {
const tempDate = Date.parse(date);
if (tempDate === searchDate) {
foundDates.push(date);
}
});
return foundDates;
}
console.log(findDates(userInput));
if there's more to consider, please say so
Have the format of date strings(input) and the array of dates be properly specified for parsing. Then you could straight away use the isSame() to check if the dates are equal
let input = "2020-06-03";
let arr = [
"2020-06-03T00:00:00.000Z",
"2020-06-05T00:00:00.000Z",
"2020-06-07T00:00:00.000Z"
];
let result = arr.map(item =>
moment(item, "YYYY-MM-DD hh:mm:ss zz").isSame(input, "YYYY-MM-DD")
);
console.log(result);
<script src="https://momentjs.com/downloads/moment.js"></script>

lodash - order dates with skipping year value

var dates = ['2017-02-01', '2017-01-01', '2016-02-03', '2018-02-02', '2014-12-25'];
var orderedDates = dates.sort(); // ['2017-01-01', '2017-02-01', '2018-02-02', '2016-02-03', '2014-12-25']
I have collection of dates(moment objects) from different year. I need to sort this dates only by 'ddMM' format (like skip years).
Is there any way to do this?
create copy of dates array, set same year for all dates - not seem like good solution.
for sorting use lodash .orderBy
You should use the 'MMDD' format and not 'DDMM'.
And it is not necessary to convert it back to a moment, since it is just to sort the array.
var orderedDates = _.orderBy(dates, e => moment(e).format('MMDD'));
You can use orderBy with an array of functions that specify your desired order (where the functions get the date and month from the moment object):
const date = (s) => moment(s, 'YYYY-MM-DD');
const dates = [date('2017-02-01'), date('2017-01-01'), date('2016-02-03'), date('2018-02-02'), date('2014-12-25')];
const result = _.orderBy(dates, [m => m.date(), m => m.month()]);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Convert String to Date Object in Array

I have a table which has a date string in the header. It is returned as part of an array but I need that date in the array to be a Date Object and not just a string.
My table is as follows
DEMO
// [[20th Jan, 33], [21st Jan, 44], [22nd Jan, 5],[23rd Jan, 17]]
I use the following JS to get this array
var arr = $.map($('#bookedTable th:not(:first)'), function(el,i) {
return [[$(el).text(), $('#bookedTable td:eq('+i+')').text()]]
});
console.log(arr)
Question: How can I return the string dates as date objects in my array?
You need to ran something like this function on all your dates in array :)
function parseThisDate(date) {
dateParts = date.split(" ");
return new Date(dateParts[2], translateMonthToNum(dateParts[1]), dateParts[0])
}
function translateMonthToNum(monthName) {
if (monthName == 'Jan,') return 0;
//todo: add all months you need
}
You can always convert a string to date as
var myDate = new Date("2013/1/16");
You can clearly get the "2013/1/16" from the array provided the months are in numbers.
click here for more info on date object in JavaScript.

Categories