Convert String to Date Object in Array - javascript

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.

Related

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>

How do I convert strings into dates in Javascript? [duplicate]

This question already has answers here:
Parse date without timezone javascript
(16 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
I have a list of string dates that I retrieve from a website.
const appDate = await page.evaluate(() => {
const dates = Array.from(document.querySelectorAll('li.det-comment-list-every div.comment-date'))
return dates.map(font => font.textContent)
});
I tried to convert them into Date objects in a for loop.
Example of appDate array :
['2018/8/22 13:52', '2018/5/11 22:36', '2018/7/20 07:13', '2018/5/30
04:04', '2018/3/26 18:21', '2019/3/20 17:46', '2019/3/18 13:01',
'2019/3/18 07:27', '2019/3/17 23:10', '2019/3/17 20:39' ]
let nDates = [];
for(let date of appDate){
var d = new Date(date);
nDates.push(d);
}
console.log(nDates);
However, the console gives me "invalid date".
[ Invalid Date,
Invalid Date,
Invalid Date,
Invalid Date,
Invalid Date,
Invalid Date,
Invalid Date,
Invalid Date,
Invalid Date,
Invalid Date ]
How can I get my dates to convert into date format?
You might have confused that for..of with for..in, vice versa. You have to be careful with iterating arrays using for..in, it iterates through enumerable properties of an object as well. Try doing this instead:
const dates = ['2018/8/22 13:52', '2018/5/11 22:36', '2018/7/20 07:13', '2018/5/30 04:04', '2018/3/26 18:21', '2019/3/20 17:46', '2019/3/18 13:01', '2019/3/18 07:27', '2019/3/17 23:10', '2019/3/17 20:39' ]
const nDates = [];
for(let date of dates){
const d = new Date(date);
nDates.push(d);
}
console.log(nDates);
If you insist on using a for..in loop, you will need to iterate via its key-value pairs:
const nDates = [];
for(let index in dates){
const d = new Date(dates[index]);
nDates.push(d);
}
console.log(nDates);
Or better still, a shorter, one-liner approach:
const nDates = dates.map(date => new Date(date));
console.log(nDates);
This is a case of wrong use of for..in.. loop. If you try to log your date in for in loop, you'll see that date is actually the index of the element.
var appDate = ['2018/8/22 13:52', '2018/5/11 22:36', '2018/7/20 07:13', '2018/5/30 04:04', '2018/3/26 18:21', '2019/3/20 17:46', '2019/3/18 13:01', '2019/3/18 07:27', '2019/3/17 23:10', '2019/3/17 20:39' ]
let nDates = [];
for(let date in appDate){
console.log(date); // 0 1 2 3 4 5 6 7 8 9
var d = new Date(date);
nDates.push(d);
}
You can use for..of or any other for loop or map to get the converted dates.
Now that you've updated the question, please verify that the dates array contains valid dates by logging them in the loop.

Sort an array of strings that are dates JavaScript

I've tried using underscorejs, min and max methods but they can't handle strings. From what i've read and learnt anyway, since I get infinite back from both.
My array looks like : dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"]
How can I grab the last and the first date in these?
I tried using sort also that looks like : _.chain(dateData).sort().first().value() but I get back the last item in the array rather then the last date in the array.
var dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"];
function dateToNum(d) {
// Convert date "26/06/2016" to 20160626
d = d.split("/"); return Number(d[2]+d[1]+d[0]);
}
dateData.sort(function(a,b){
return dateToNum(a) - dateToNum(b);
});
console.log( dateData );
To retrieve the first, last date:
var firstDate = dateData[0];
var lastDate = dateData[dateData.length -1];
Basically, if you first convert all your 26/06/2016 to a date Number like 20160626 you can .sort() those numbers instead.
so you're basically sorting:
20140626
20140604
20140513
20140720
resulting in:
[
"13/05/2016",
"04/06/2016",
"26/06/2016",
"20/07/2016"
]
If we can format the dateStrings in a particular format, then sorting them as strings also sorts them as dates e.g. YYYY-MM-DD.
You can use localeCompare to compare strings.You can use following code to sort the dates:
dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"]
dateData.sort(function(a, b){
var A = a.split("/");
var B = b.split("/");
var strA = [ A[2], A[1], A[0] ].join("/");
var strB = [ B[2], B[1], B[0] ].join("/");
return strA.localeCompare( strB );
});
console.log( dateData );
Once sorted, you can get the min and max dates as:
var minDate = dateData[0];
var maxDate = dateData[ dateData.length - 1 ];
The getTime() method returns the numeric value corresponding to the
time for the specified date according to universal time. Date.getTime()
dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"]
.map(a=>a.split('/').reverse().join('/'))
.sort((a,b)=>new Date(a).getTime() - new Date(b).getTime());
console.log(dateData);
A number people have already touched on this, but you need to convert the date strings to something that can be compared in the sort function. The one thing I haven't seen shared is how to get the first and last dates. This should do the trick:
//original date array
var dateData = ["04/06/2016", "13/05/2016", "20/07/2016","26/06/2016"];
//map through the original array and convert the dates to js date objects
var formattedDates = dateData.map(function(date){
var splitDate = date.split("/")
return new Date(splitDate[2],splitDate[1]-1,splitDate[0])
})
//sort the dates
formattedDates.sort(function(a,b){
// Turn your strings into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(a) - new Date(b);
});
//Now you can get the first and last dates:
var firstDate = formattedDates[0]
var lastDate = formattedDates[formattedDates.length-1];
//log to check:
console.log('first date: ', firstDate)
console.log('last date: ', lastDate)
One way I know to do this is using the .sort() function for a string. https://msdn.microsoft.com/en-us/library/4b4fbfhk(v=vs.94).aspx
You would have to change your array into YYYY-MM-DD
then you could have the following code
var dateData = ["2016/06/26", "2016/06/04", "2016/05/13", "2016/07/20"];
dateData.sort();
var first = dateData[0];
var last = dateData[dateData.length-1];
where first is the earliest date and last is the latest date
To be easier for the subsequest operations, change the format to be like this: YYYY/MM/DD.
This way regular sorting will get you the min and max properly, and you won't need further parsing.
Helper function to sort would be like this:
for(var i=0;i<dateData.length;++i)
{
var split = dateData[i].split("/");
dateData[i] = split.reverse().join("/");
}
Roko's answer worked for me, and +1. And Jose had a similar thought to me, +1...
...There's an easier and more robust way: .valueOf()
converting date string to number:
const dateAsNumber = new Date(dateAsString).valueOf()
JS has a built in method/function for calculating the number of milliseconds that have passed since a date; that's .valueOf(), which can be called on a Date object. So, turn your date string into a Date object (with "new Date()" with the date string as the argument), and then convert to milliseconds.
After that, the normal .sort() works fine. As shown below, for your convenience:
const arrayOfDateStrings = ["5/01/2012", "10/01/2020", "10/01/2019", "11/30/2016", "10/01/2021", "02/01/2020"];
const sortedArray = arrayOfDateStrings.sort((a,b)=>new Date(a).valueOf() - new Date(b).valueOf());
console.log(sortedArray);
Or Moment.js can be used instead of the built-in Date object/functions, that works in a very similar way.

Calculating Date difference and matching it with array

Is there any way in JavaScript that I can check if date is between 2 dates?
I have an array like
var unavailableDates = ["5-7-2011","6-7-2011","7-7-2011","15-7-2011","16-7-2011","17-7-2011" ];
and now I have 2 dates like 1-7-2011 and 10-7-2011. I want to see if any value from unavailableDates falls between these date. If it falls it should return alert.
Can someone help me on this? I am in process of learning more about JavaScript and jQuery. I am not able to code it the way I understood the problem.
Here you have the solution
var unavailableDates = ["5-7-2011","6-7-2011","7-7-2011","15-7-2011","16-7-2011","17-7-2011" ];
function str2date(sdate){ //This function gets a string and return a Date object
var parts = sdate.split("-");
return new Date(parts[2], parseInt(parts[1], 10)-1, parts[0]);
}
var stamp1 = str2date("1-7-2011").getTime(); //First date. getTime() converts it to an integer
var stamp2 = str2date("10-7-2011").getTime(); //Second date
for(var i=0; i<unavailableDates.length; i++){
var curStamp = str2date(unavailableDates[i]).getTime();
if(curStamp >= stamp1 && curStamp <= stamp2) //Check if it falls in range
alert(unavailableDates[i] + " falls in range");
}
Hope this helps. Cheers
Date object in JavaScript allows compare operation, you only required to have proper Date objects. Create Date objects from your bounds and array members and compare them in a loop.
More information about Date object could be found there: http://www.w3schools.com/js/js_obj_date.asp

Categories