I have a data array which has a date attribute, I need to filter the data based on date.
I am using dstorejs to store the data as below
this.employeeStore = new Memory({data:[emplist],idProperty:"emp_num"});
I need to make a filter based on employee's joining date , like who joined from 1st of Jan 2014 till 3rd of March 2015
this.employeeStore.filter({joinDate:'01/01/2014'});
This gives all employees who joined on 1st of Jan 2014 but if I need to filter in a range like
this.employeeStore.filter.gte({joinDate:'01/01/2014'});
This will not work because it is not a number, it is a string or date object
To achieve this do I need to write the custom store as they mentioned in tutorial?
Is there any other way of doing this?
Or is there any other framework like dstore to achieve this ?
You can achieve this just by using dojo/store Query filter ,
exactly query with callback function to manage comparing date
and also using the dojo/date compare function to compare date of your emplist array to a specific date like below :
this.employeeStore = new Memory({data: someData});
var compareDate = new Date(2014,1,1);
var results = store.query(function(object){
// compare return -1 if lower
// return 0 if equals
// return 1 if greater
return date.compare(object.date, compareDate) > -1;
});
results.forEach(function(yourResultData){
// some stuff looping results
});
you can see a Fiddle to have a better understanding .
Related
If I had an array of dates, is there a way I could match up another date by rounding up until one is matched?
For example, say I have an array of dates:
"2022-09-15"
"2022-10-10"
"2022-12-01"
And I have a date pulled from the application: "2022-09-29", I want the date to update itself by rounding up until the next upcoming date ("2022-10-10") is selected.
I am unsure how I would round up like I could in mathematics situations.
Assuming your dates are in order, you can iterate through your array starting at the beginning until you find the first date that is bigger than you date provided by the application. In JavaScript, your can do a direct comparison like this:
"2022-09-15" > "2022-10-10" // false
"2022-09-15" < "2022-10-10" // true
Note that this works because of the ordering of the year, month, and day that you have presented. If you wanted to do comparisons where you had day, month, year, you would want to create a Date JavaScript object and do the comparisons that way. You can read more about those here: Compare two dates with JavaScript
But for your use case, a simple loop could look like this:
for(let i = 0; i < array.length; i++) {
if(applicationDate < array[i])
return array[i]
}
You don't necessarily need to "round" the dates up. Incrementing the date and comparing it to every entry in the array until you find a match would take a relatively large amount of time and resources. I prefer a kind of "knock-out" approach to problems like this. Simply rule out everything it can't be until you're left with a single option. In this case, since you specifically need a date that comes after the input date, we can first rule out anything before the input date. We can then take this new list of dates (that we now know are all after the input date) and get the "smallest" one. This will effectively give you the date that is closest to the input date but still after it.
In your question you presented the dates as a list of strings. This isn't a huge deal because this can still be fairly easily accomplished, but the strings must be in a format that JavaScript recognizes as a date, otherwise all comparisons will result in false. Here is a list of the valid date formats.
I personally like to avoid depending on the order of arrays just because it can be hard to maintain and if/when it breaks, it's generally very hard to find that the issue is that the array is out of order (speaking from experience here). For this reason, the code examples provided here will be completely unreliant on the order of the array.
First, let's discuss a solution using Date objects. This is fairly straight forward. The only thing is that you would need to make sure the date being input is in a valid format as discussed previously. Keep in mind the input needs to be converted to a Date object (if it isn't already) because comparisons between date strings and Date objects always return false. To get only dates after the current date, we can use Array.prototype.filter(), and to get the "smallest" date afterwards we can use Math.min.apply() as explained in this Stack Overflow answer.
var dates = [
new Date("2022-09-15"),
new Date("2022-10-10"),
new Date("2022-12-01")
];
var inputDate = new Date("2022-09-29");
var datesAfter = dates.filter(x => x > inputDate);
var closestDate = new Date(Math.min.apply(null,datesAfter));
console.log(closestDate);
Now for date strings. The idea is largely the same as Date objects. The only difference really is that we can't use Math.min.apply() on date strings. We can however use Array.prototype.reduce() in order to compare all the dates, it's just a bit more involved.
var dates = [
"2022-09-15",
"2022-10-10",
"2022-12-01"
];
var inputDate = "2022-09-29";
var datesAfter = dates.filter(x => x > inputDate);
var closestDate = dates.reduce((a, b) => a > b ? a : b);
console.log(closestDate);
Suppose I have ISO Date inside an object as:
const dataCreated = {"readDetail":'2020-09-17 14:23:26.978Z'}
Is it possible to I get all date from created date till todays date.
Expected O/P ->assunming current date is jan 2021 :
['2020-09-17','2020-10-17','2020-11-17','2020-12-17','2021-01-17']
I tried different searches but was unable to get find anything related to it. If anyone has any solution or in someway can guide me that would be really helpful. If any further information needed please let me know.
What you want to do is just fill your array while looping over the dates. And with each loop add one month to your original date.
Note that you have to to create a new Instance of Date before saving it in your array since JavaScript saves references.
function getDates() {
var date = new Date("2020-09-17 14:23:26.978Z");
var now = new Date();
var datearray = [new Date(date)];
while(date.setMonth(date.getMonth() + 1) < now) {
datearray.push(new Date(date));
}
console.log(datearray);
}
Contrary to your expected output I'm saving Date Objects in the array. This has the advantage of giving you more opportunities when working with the Array elements afterwards. This could easily be changed though by changing the line where the Date object is pushed to the array.
I've been using the below code to transform a large list of dates in a array of counts which i can then use in a simple line chart. The issue i'm encountering is with sorting the values by the year and week number. When i have data such as [{201501: 20},{201502: 20},{201451: 20},{201452: 20}] i need to sort the array by the key name into the following format [{201451: 20},{201452: 20},{201501: 20},{201502: 20}]. They i simply discard the key with _.values()
How do i go about ordering the array with underscore, i've tried a few things but i'm pretty lost at this point.
var graphData = _.chain(thisYearFiltered)
// map each string like '2014-01-01 00:00:00' using moment.js to the ISO Week. ISO weeks are used because they run Monday to Sunday
.map(function(date){
return moment(date, "YYYY-MM-DD HH:mm:ss").isoWeekYear() + moment(date, "YYYY-MM-DD HH:mm:ss").isoWeek();
})
// Manipulate weeks numbers [201423,201423,201423,201423,201424] into a count for each like [{201423:4 },{201424:1}]
.countBy(function(num) {
//console.log(num);
return num;
})
// Pull out the values of the objects and discard the week number. [{23:4 },{24:1}] to [4,1]
.values()
.value();
I know this is all possible with underscore but i've hit a wall with this one so any suggestions would be welcome.
I've looked into _.sortBy() but that seems to expect a named key to sort on and in my case the keys names are all different. Could i do something similar with the first key?
For objects, sortBy also passes the key to the callback as the second argument and only keeps the value of the object after sorting it, so:
_.chain([201423, 201423, 201423, 201423, 201424]).
countBy(function(n) { return n; }).
sortBy(function(v, k) { return k; }).
value()
gives
[ 4, 1 ]
I'm trying to figure out what the best way to store date in DB is. Using
new Date().getTime()
seems to be the most common but is it possible to get the year/month/date from the timestamp? or is getTime meant as a way to sort data. Should I just store new Date() directly if I want retrieve the y/m/d information again?
Thanks
var dateObject = new Date();
var year = dateObject.getYear();
var month = dateObject.getMonth();
var date = dateObject.getDate();
getTime() is useful for saving in files and databases because it represents the date and time as a single number, which is very compact. It's also represented in UTC, so the timezone doesn't matter.
You can convert it back to a Date with:
var thatTime = Date(retrievedTime);
Then you can use thatTime.getYear(), thatTime.getMonth(), etc. to extract parts of the saved time.
#Barmar is absolutely correct. However, if you want the year, month and date information stored in an easily readable way, you can go two ways (assuming you only want the date and not the time):
Use the Date object's getYear, getMonth and getDate methods respectively and store them in separate fields (less processing for display and you can choose which parts you want, but more parsing required for sorting, etc.)
toDateString (and toLocaleString for non-American-English and flexibility) gives a human-readable string like "Wed Jul 28 1993" (and then you'd slice off the first 4 characters).
I have 2 dates and I one to check if one date comes before another one.
I know you have to parse the date to a JS date object and then check it with milliseconds.
But the problem is, in my database dateTimes are stored like this.
10-mei-2012 09:36
So my question is how can I compare two of these dates and check that date 1 comes before date2? Oh and for the record, I am also using jquery to get these values.
var dateB = $('#DATUM_BEGIN').val();
var dateE = $('#DATUM_EINDE').val();
kind regards
Stef
In that format you can compare strings as-is, it is safe. So use just
if (dateB < dateE) ...
http://www.datejs.com/ could be helpful. it is a jquery Plugin to compare Dates.
The format you show is "mostly" ISO-8601 combined-date format which is by design comparable as plain text.
The only difference between what you have and pure ISO-8601 is that there would need to be a 'T' where the space character is.
http://en.wikipedia.org/wiki/ISO_8601
So, if you can sort the strings you know which one comes first.
Here's a function found while googling that converts MySQL DATETIME to a JS Object
function mysqlTimeStampToDate(timestamp) {
var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
}
Here's one example of how to use it:
$(function(){
var dateB = mysqlTimeStampToDate($('#DATUM_BEGIN').val());
var dateE = mysqlTimeStampToDate($('#DATUM_EINDE').val());
if(dateB < dateE){
// dateB is older
} else {
// dateB is newer
}
});