Sorting JSON object in javascript by date (String) - javascript

I have a JSON object in JavaScript and I am trying to sort the object in order by dates.
fileListObj[id] = date;
output : "#HIDDEN ID": "16/12/2013"
How can I sort the object to be in order by most recent date?
I only know how to do this in php

include moment.js
fileListObj.sort(function(a,b) {
return moment(b, 'DD/MM/YYYY').valueOf() - moment(a, 'DD/MM/YYYY').valueOf();
})

First you'll want to write/get a date parser. Using Javascript's native Date object is unreliable for parsing raw strings.
Then you'll want to use Array.prototype.sort():
function parseDate(input) {
var parts = input.split('/');
return new Date(parts[2], parts[1]-1, parts[0]);
}
function sortAsc(a,b)
{ return parseDate(a.date) > parseDate(b.date); }
function sortDesc(a,b)
{ return parseDate(a.date) < parseDate(b.date); }
list.sort(sortAsc);

Here's a working example, the sorted table will contain ISO format dates
var dates = ["12/05/2012", "09/06/2011","09/11/2012"]
var sorted=[];
for(var i=0, i= dates.length;i++){
var p = dates[i].split(/\D+/g);
sorted[i]= new Date(p[2],p[1],p[0]);
}
alert(sorted.sort(function(a,b){return b-a}).join("\n"));
To get the same input format you can use this function:
function formatDate(d)
{
date = new Date(d)
var dd = date.getDate();
var mm = date.getMonth()+1;
var yyyy = date.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm};
return d = dd+'/'+mm+'/'+yyyy
}
sorted.sort(function(a,b){return b-a})
formatSorted = []
for(var i=0; i<sorted.length; i++)
{
formatSorted.push(formatDate(sorted[i]))
}
alert(formatSorted.join("\n"));

Related

Comparing Dates with Javascript does not work

Moment.js is driving me nuts.
I have dates in this format
10-Jul-2019 inside my array of objects alldata and here is my code:
I need to filter out the objects where DueDate is outside of the range of last 90 days.
The issue is that the comparisons is not working properly...it's telling me that
11-05-2019 > 08-08-2019
Am I missing something or is there a bug in moment.js? Feel free to suggest any method that does not use moment.js
var todate = moment().format("DD-MM-YYYY");
var fromdate = moment().subtract(90, "days").format("DD-MM-YYYY");
var data = [];
for (i = 0; i < alldata.length; i++) {
duedate = moment(alldata[i].DueDate, "DD-MMM-YYYY").format('DD-MM-YYYY');
if ( duedate >= fromdate) {
alert("good!");
} else
alert("bad!");
}
You are not comparing integers or numbers format returns a string.
Why not using the isAfter built-in method from moment.js library which compares two "moments".
var fromdate = new moment().subtract(90, "days");
for (i = 0; i < alldata.length; i++) {
let checkDate = new moment(alldata[i].DueDate,"DD-MMM-YYYY")
let isAfter = checkDate.isAfter(fromdate);
if ( isAfter ) {
alert("good!");
} else
alert("bad!");
}
You're comparing strings, because you're formatting the date before the compare.
This is a moment.js self-contained example:
//Include https://momentjs.com/downloads/moment.js
var oldDate = new moment('11-Jan-2018', 'DD-MMM-YYYY');
var newDate = new moment('01-Feb-2018', 'DD-MMM-YYYY');
if (newDate.isAfter(oldDate)) {
alert('it works');
}
else {
alert('no workie');
}
https://jsfiddle.net/h3yf5r60/4/
Use this snippet as an example for plain JS:
var now = new Date();
var yesterday = new Date();
yesterday.setMonth(yesterday.getMonth() - 1);
if (now > yesterday) {
alert('it works');
}
else {
alert('no workie');
}
https://jsfiddle.net/Lobpk519/

Get localized month name using native JS

It's possible to do this to get the localized full month name using native javascript.
var objDate = new Date("10/11/2009"),
locale = "en-us",
month = objDate.toLocaleString(locale, { month: "long" });
But this only gets the month number for a given date. I'd simply like to get the month name corresponding to a month number. For example, if I do getMonth(2) it would return February. How can I implement getMonth using native javascript(no libraries like moment)?
You are already close:
var getMonth = function(idx) {
var objDate = new Date();
objDate.setDate(1);
objDate.setMonth(idx-1);
var locale = "en-us",
month = objDate.toLocaleString(locale, { month: "long" });
return month;
}
console.log(getMonth(1));
console.log(getMonth(12));
To get all the months of a year and days of the week, loop over a set of dates and use toLocaleString with appropriate options to get the required values:
function getLocalDayNames() {
let d = new Date(2000,0,3); // Monday
let days = [];
for (let i=0; i<7; i++) {
days.push(d.toLocaleString('default',{weekday:'long'}));
d.setDate(d.getDate() + 1);
}
return days;
}
console.log(getLocalDayNames());
function getLocalMonthNames() {
let d = new Date(2000,0); // January
let months = [];
for (let i=0; i<12; i++) {
months.push(d.toLocaleString('default',{month:'long'}));
d.setMonth(i + 1);
}
return months;
}
console.log(getLocalMonthNames());
The language default means toLocaleString uses the default language of the implementation that the code is running in.

How to filter the data using date from JSON format

I want to filter using date but the data is in JSON format. How can I filter the large dataset using date in JavaScript?
Example:
data=[{date:'22-12-2014',name:'selva'},{date:'10-10-2010',name:'raja'},{date:'11-11- 2011',name:'suresh'}]
If you simply want to filter data by time, you can look through all objects in the array like this:
var filteredData = [];
for(var index in data) {
var obj = data[index];
var date = parseDate(obj.date);
//Filter dates from 2011 and newer
if(date > new Date(2011, 0, 1))
filteredData.push(obj);
}
function parseDate(dateStr) {
var date = dateStr.split('-');
var day = date[0];
var month = date[1] - 1; //January = 0
var year = date[2];
return new Date(year, month, day);
}
//Filtered data now contains:
// [{"date":"22-12-2014","name":"selva"},{"date":"11-11- 2011","name":"suresh"}]
I am sure you could do the parse date better, by for example defining the date in a format that the Date constructor accepts.
To grab the set of elements that match a certain date you can use filter to extract them into a new array.
function getByDate(date){
return data.filter(function (el) {
return el.date == date;
});
}
var arr = getByDate('11-11-2011');
To to sort your dataset by date you need to convert your date strings to a JS date object first. That involves adjusting the date string slightly so it can be parsed properly.
function reformatDate(date) {
return arr = date.split('-').reverse();
}
var sortByDate = function (a, b) {
return new Date(reformatDate(a.date)) - new Date(reformatDate(b.date));
};
data.sort(sortByDate);
JSFiddle demo
I used date format MM/DD/YY. Here is the full example -
var data=[
{date:'02/10/2018',name:'date is 10'},
{date:'02/14/2018',name:'date is 14'},
{date:'02/16/2018',name:'date is 16'},
{date:'02/20/2018',name:'date is 20'},
{date:'02/24/2018',name:'date is 24'},
{date:'02/26/2018',name:'date is 26'},
{date:'02/30/2018',name:'date is 30'},
{date:'03/01/2018',name:'date is 01'},
{date:'03/05/2018',name:'date is 05'},
{date:'02/23/2018',name:'date is name 23'},
]
var today = new Date();
var todayTime = new Date().getTime();
var days_after_20 = new Date().setDate(today.getDate()+20);
var days_before_5 = new Date().setDate(today.getDate()-5);
var result = data.filter(function (item) {
var itemTime = new Date(item.date).getTime()
return itemTime >= days_before_5 && itemTime <= days_after_20;
})
console.log(result);
To fetch the set of elements that match a certain date you can use filter to extract them into a new array.
var tempArray= data.filter(function (d, i) {
return d >= startDate && d <= endDate;
})

how to sort milatry format date in javascript

i want to sort date in ascending order in javascript function.i am having date in following format 3/4/2014 1300
im having follwing array which contains date
categoriesdata.push(RecordDate);
categoriesdata.sort(function (a, b) {
var key1 = a.RecordDate;
var key2 = b.RecordDate;
if (key1 < key2) {
return -1;
} else if (key1 == key2) {
return 0;
} else {
return 1;
}
})
categoriesdata have the following record
3/4/2014 1300
2/4/2014 0000
1/31/2014 1030
now i want to sort these record in such way so that i will get following output
1/31/2014 1030
2/4/2014 0000
3/4/2014 1300
you have to split the date string and get the parts using regex or simple split
var date = "1/31/2014 1030".split(" ");
var day = parseInt(date[0].split["/"][0], 10);
var month = parseInt(date[0].split["/"][1], 10) - 1;
var year = parseInt(date[0].split["/"][2], 10);
var hours = parseInt(date[1].slice(0,2), 10);
var minutes = parseInt(date[1].slice(2,4), 10);
then create Date objects from them in javascript.
var dateObj = new Date(year, month, day, hour);
then convert the dates to be compared to "milliseconds since beginning"
var milliseconds1 = Date.parse(dateObj)
similarly convert both dates to be compared in milliseconds, now you will have two numbers that can easily be compared
Incorporate this idea to your sort function.
categoriesdata.push(RecordDate);
categoriesdata.sort(function (a, b) {
var key1 = a.RecordDate;
var key2 = b.RecordDate;
var getTimestamp = function (dateString) {
var date = dateString.split(" ");
var day = parseInt(date[0].split["/"][0], 10);
var month = parseInt(date[0].split["/"][1], 10) - 1;
var year = parseInt(date[0].split["/"][2], 10);
var hours = parseInt(date[1].slice(0, 2), 10);
var minutes = parseInt(date[1].slice(2, 4), 10);
return Date.parse(new Date(year, month, day, hour));
}
key1 = getTimestamp(key1);
key2 = getTimestamp(key2);
if (key1 < key2) {
return -1;
} else if (key1 == key2) {
return 0;
} else {
return 1;
}
})
Best way is to convert it to a date type. And after sorting convert it back to the string you want
For sorting dates there are plenty of solutions. Read this Sort Javascript Object Array By Date

If date between date range

I'm working with two dates, e.g. 29/03/2014 and 04/04/2014, and I have an array of dates e.g. 01/04/2014 and 02/04/2014, I need to find out how many (if any) dates in that array are between the date range.
What's the best way to do this?
EDIT: Final code, tweaked a little from ponciste's answer
//date1 and date2 are the start/end dates
bhDays = new Array();
$.each(DataBridge.bankHolidays, function(i, v) {
var americanDate = v.split('-');
americanDate = americanDate[1] + '/' + americanDate[0] + '/' + americanDate[2];
date = new Date(americanDate);
if (date1 <= date && date2 >= date) {
bhDays.push(date);
}
});
it's better to deal with Date object in this case
so your code should be something like this:
var strDateFrom = "29/03/2014";
var strDateTo = "04/04/2014";
var dateFrom = strDateFrom.split("/");
var dateTo = strDateTo.split("/");
var dates = ["01/04/2014", "02/04/2014"];
var from = new Date(dateFrom[2], dateFrom[1]-1, dateFrom[0]);
var to = new Date(dateTo[2], dateTo[1]-1, dateTo[0]);
dates.forEach(function(date) {
var dateToCheck = new Date(date[2], date[1]-1, date[0]);
if(dateToCheck > from && dateToCheck < to)
});
The Date object will do what you want - construct one for each date, then just compare them using the usual operators.
Construct your date objects and compare using < || > operators.
I strongly reccoment to use moment.js library for that (and all other operations with date/time) and use difference function.

Categories

Resources