Difference between two isodates in mongo - mongodb

If I have two ISODates such as:
Tue Sep 18 1984 00:00:00 GMT+0100 (CET)
and
Sat Jun 21 2014 10:00:00 GMT+0100 (CET)
how do I get a difference between them using the mongo console? Specifically the difference in years?
they are from different collections so I can't use an aggregation for this.. :(

ISODate() is just a convenient wrapper around a standard JavaScript Date object so you can use the standard Date methods or calculate the difference yourself (date values are stored in milliseconds):
> var date1 = ISODate("1984-09-18");
> var date2 = ISODate("2014-06-21");
> date2.getFullYear() - date1.getFullYear()
30
> var yearMS = 365 * 24 * 60 * 60 * 1000; // a year in milliseconds
> parseFloat((date2-date1)/yearMS).toFixed(2)
29.78

Related

How can compare Date on mongo without time?

This is a sample data
[{ date: '2020-05-21T14:02:00.0123 }, { date: '2020-05-22T14:02:00.0123 }, { date: '2020-05-23T14:02:00.0123 }]
I want to filter records of 22-May or earlier, here is my expected:
[{ date: '2020-05-21T14:02:00.0123 }, { date: '2020-05-22T14:02:00.0123 }]
I tried with this query:
{ date: { $lte: new Date('2020-05-22') }}
But it returns only data earlier 22-May. I think problem is { date: { $lte: new Date('2020-05-22') }} will data.date lte 2020-05-22T00:00:00.000
How I can exclude time ?
You need to match type of input with type of date field in document, either both should be Date's or strings. I would highly suggest maintain dates as dates in DB. Also you need to know that dates in MongoDB are of format ISODate() and holds UTC date.
If your DB date field is of type date :
I want to filter records of 22-May or earlier
As you wanted to get documents <= 22-May, then sending new Date('2020-05-22') doesn't work. Cause :
when you do new Date('2020-05-22'), it will give you Fri May 22 2020 00:00:00 GMT only if you belong to UTC, for example if you're in New York America which is 4 hours behind UTC then it would result in Thu May 21 2020 20:00:00 GMT-0400 (Eastern Daylight Time) which represents EDT, basically it's your system/app server time i.e; local date time.
So if your region is behind UTC then you'll get a back date Thu May 21 2020 otherwise if it's ahead of UTC then there is no issue you'll see Fri May 22 2020.
Ok, now that we've fixed date issues, but we need to look into hours now :
Since you want docs <= 22-May then Fri May 22 2020 00:00:00 GMT doesn't work you need to have either <= Fri May 22 2020 23:59:59 GMT or Sat May 23 2020 00:00:00 GMT. In order to get that :
let date = new Date('2020-05-22')
date.setDate(date.getUTCDate()); // Setting utc date, Only useful if you're region is behind UTC
date = new Date(date.setHours(23,59,59,999)) // This overrides hours generated with 23:59:59 - which is what exactly needed here.
/** Now do your query */
{ date: { $lte: date }}
If your DB date field is of type string :
Then you don't need to convert string to date, instead you can send input date in string format :
let date = new Date('2020-05-22').toISOString() // 2020-05-22T00:00:00.000Z
/** Above would get you an ISO string no matter which region you're in, 
* now since we need `2020-05-22T23:59:59.000Z` which is not easy on ISO string
* We would just do +1 on date like `new Date('2020-05-23').toISOString()` - // 2020-05-23T00:00:00.000Z */
let date = new Date('2020-05-23').toISOString(); // like this
date = date.slice(0, -1) // removing `Z` from date string as your `date` field doesn't have this.
// Now your query is just `$lt`
{ date: { $lt: date }}
Test : mongoplayground

How to get current month from the selected date in GWT?

Date startDate = new Date(Long.valueOf(""05/07/2018")getValue().toString());
get last day of selected month is required
private Date lastDayOfMonth(Date month) {
Date lastDay = (Date) month.clone();
CalendarUtil.addMonthsToDate(lastDay, 1);
CalendarUtil.setToFirstDayOfMonth(lastDay);
CalendarUtil.addDaysToDate(lastDay, -1);
GWT.log("lastDay :: "+lastDay);
return lastDay;
}
I get lastDay :: Tue Jul 31 00:00:00 GMT+530 2018
But i get 30th instead of 31st
First, your code does not work
Date startDate = new Date(Long.valueOf(""05/07/2018")getValue().toString());
Second, your method private Date lastDayOfMonth(Date month) looks fine, I have a test and got result Tue Jul 31 00:00:00
I dont understand your problem "Tue Jul 31 00:00:00 GMT+530 2018 But i get 30th instead of 31st". How can you get 30th from Tue Jul 31 00:00:00 GMT+530?

Date minus date is not giving desired answer - IONIC 2

When I try to subtract
Wed Dec 06 2017 15:58:59 GMT+0530 (India Standard Time) minus Tue Nov 28 2017 00:00:00 GMT+0530 (India Standard Time) , the answer which is coming is -22
But the answer should be 6
What is going wrong and where, below is my page.ts code:
this.tt = new Date();
this.tt1 = this.datePipe.transform(this.tt,'dd/mm/yyyy');
console.log(this.ent[0],"server DATE");
// in console we see this - 28-NOV-17 server DATE
var firstDate= new Date(this.ent[0]); //Jan 01 2017 00:00:00
var secondDate = new Date();//Jan 04 2017 00:00:00
console.log(firstDate);
// answer in console - Tue Nov 28 2017 00:00:00 GMT+0530 (India Standard Time)
console.log(secondDate);
//answer in console - Wed Dec 06 2017 15:58:59 GMT+0530 (India Standard Time)
console.log(secondDate.getDate() - firstDate.getDate() );
//answer in console - -22
Date.getDate() gives the "dd" of the date (in your case 6 and 28 which explains the result being -22).
I'm a bit confused with the expected result being 6. So maybe my answer won't fit you. What I would do however is convert the date in time, do the substraction and convert it back to number of days.
So
Math.Floor((secondDate.getTime() - firstDate.getTime()) / 86400000);
(86400000 being 1000 (milliseconds) * 3600 (seconds in an hour) * 24 (number of hours in a day)
you can convert both dates to timestamp and subtract the timestamp you will get the result days in millis now convert it to days
getTimestamp(dateParam:string):string{
var date = new Date(dateParam); // some mock date
var milliseconds = date.getTime();
return milliseconds.toString();
}
var one_day=1000*60*60*24;
console.log(Math.ceil(getTimestamp(secondDate) - getTimestamp(firstDate))/(one_day) );

Angular2 - convert unfortunately date

I have a problem - I use c# Web.api and Angular2. Thats works but Angular convert the date which I do not want / need. The date of the database is correct and angular add 1 hour
{{item.createdate | date:'H:mm' }}
So it shows 20:30 instead of 19:30 which is stored in the database :(
This is part of json repsone:
"createdate": "2016-11-29T19:30:00",
How can I solve this?
Thank you
Ralf
The Reason is there's no timezone information in the datetime string from the database result.
var date = new Date('2016-11-29T19:30:00');
console.log(date); //Tue Nov 29 2016 20:30:00 GMT+0100 (CET)
Written in the Angular2 documentation about the Date Pipe here.
The expression expects a valid datestring format:
YYYY-MM-DDThh:mmTZD (eg 2016-11-29T19:30+01:00)
var date = new Date('2016-11-29T19:30+01:00');
console.log(date); // Tue Nov 29 2016 19:30:00 GMT+0100 (CET)

IndexedDB with range queries

I would like to find which date ranges overlaps another date range in IndexedDB.
Something like the following query:
SELECT * FROM events
WHERE (periodStart >= start AND periodStart < end)
OR (start >= periodStart AND start <= periodEnd)
Events looks like the following object:
[{
title: 'foo',
start: 'Tue Oct 29 2013 10:19:52 GMT-0400 (EDT)',
end: 'Tue Oct 29 2013 13:19:52 GMT-0400 (EDT)'
},
{
title: 'bar',
start: 'Tue Oct 30 2013 00:00:00 GMT-0400 (EDT)',
end: 'Tue Oct 31 2013 00:00:00 GMT-0400 (EDT)'
}]
To my knowledge, no ability to do unions in indexeddb (the OR).
So, as that kinda sucks, here is a half thought out solution that maybe puts you on the course: something like find the min of the set, and the max of the set, and then a query descending and a query ascending but just get the first record from each cursor, and then, something.