Get every round hour from Firestore - flutter

I have a data stored in Firestore, the data add to Firestore every second, so in 24 hours I have 1440 documents (24 * 60), I want to fetch only round hour from the Firestore for show it on a Graph, how can I get only round hour from Firestore?

First of all, you will have to store the firestore documents with a timestamp property and then query the documents with the timestamp value which gives a rounded hour using DateTime and DateFormat APIs of flutter.
Once you've got a timestamp back from Firestore, something like :
Timestamp(seconds=1560523991, nanoseconds=286000000)
You can get only rounded hour from the timestamp value using 2 ways :
You need to parse it into an object of type DateTime:
DateTime myDateTime = (snapshot.data.documents[index].data['timestamp']).toDate(); // prints 2020-05-09 15:27:04.074
This will return your Firestore timestamp in the dart's DateTime format. In order to convert your DateTime object you can use DateFormat class from the intl package. You can use your obtained DateTime object to get the format of your choice like this:
Possible Solution 1 :
DateFormat.Hm().format(myDateTime); //prints 15.27
So the query should look for documents with:
DateFormat.m().format(myDateTime) to be “00” as
DateFormat.m() returns minutes and if minutes == 00 then the timestamp is rounded to the nearest hour.
Possible Solution 2 :
Convert timestamp into timestring using :
Let TimeString = snapshot.data.documents[index].data['timestamp']).toDate().toString() // prints ‘2019-12-28 18:48:48.364’
Let time = TimeString.split(“ “)[1] // prints 18:48:48.364
To check if the minutes is “00” :
if time.substring(3,5) == “00”, then it's a rounded hour. //here it is 48
You will have to put these timestamp conversion logics and then query as I mentioned for the rounded hour timestamp. There are no readymade available functions/methods to get the firestore documents with rounded hours.

Firestore supports "IN" Queries.
Store as Timestamp, and try with following
const roundhour1 = new Date('2021-10-01T01:00:00.000z');
const roundhour2 = new Date('2021-10-01T02:00:00.000z');
And then write the query like below:
database.collection("collectionName").where("fieldName", "in", ["roundhour1", "roundhour2"]);
You can have up to 10 values (roundhourX) to check "IN" of, so need to fire 3 queries to get all 24 hours data.

Related

timestamp in milliseconds and date range - elasticsearch query string

I have a timstamp in milliseconds, like 1645825932144
I'd like to make a date range query with elastic search query string for being able to get all records whom timestamp is in the last 24h:
timestamp:[now-24h TO now]
This does not work as timestamp is in milliseconds and now produces strings like 2001-01-01 13:00:00
Is it possible to achieve this with a cast or something?
I read about range queries and date math, but did not find anything.
It's easy to compute the timestamp in milliseconds for now and now-24h so why not do it in your application logic and build the query out of those values?
For instance (in JS),
const now = new Date().getTime();
const now24h = now - 86400000;
const query = `timestamp:[${now24h} TO ${now}]`;
query would contain the following value:
timestamp:[1647785319578 TO 1647871719578]
UPDATE:
PS: I might have misunderstood the initial need, but I'm leaving the above answer as it might help others.
What you need to do in your case is to change your mapping so that your date field accepts both formats (normal date and timestamp), like this:
PUT your-index/_mapping
{
"properties": {
"timestamp": {
"type": "date",
"format": "date_optional_time||epoch_millis"
}
}
}
Then you'll be able to query like this by mix and matching timestamps and date math:
GET test/_search?q=timestamp:[now-24h TO 1645825932144]
and also like this:
GET test/_search?q=timestamp:[1645825932144 TO now]

Converting timestamp object to date with difference in flutter

Let’s say I have an object of type Timestamp set to 2 days from now.
How to get the difference in time and then format it in DateFormat('hh : mm : ss') in dart ?
Construct a DateTime from the Timestamp.
Subtract from that DateTime the initial time (which I presume should be DateTime.now()) to get a Duration.
Format the Duration. Its default .toString() implementation uses hh:mm:ss.microseconds, which is close to what you want. If you want more control, you can easily format it yourself.
var dateTime = DateTime.fromMicrosecondsSinceEpoch(timestamp.timestamp!);
var duration = dateTime.difference(DateTime.now());
print(duration);

Display the difference between two Firestore Timestamp values in Flutter

I am taking startdate and endDate as input from user with DateTime as datatype in Flutter(Dart). These fields will be stored in Firestore may be as timestamp format.
Now we need to display the difference of endDate and startDate on client side which can be a live timer in format as "13 Hrs 45 mins" then after some mins it should be "13 Hrs 42 mins".
May I know how can we achieve this using Firestore or may be cloud functions for Flutter apps?
Thanks
In flutter, Timestamp can be easily converted to DateTime, and DateTime has convenient method called difference that will give you difference between two DateTime objects as Duration object.
Here is a simple example:
final Timestamp endTime = Timestamp(1000, 0);
final Timestamp startTime = Timestamp(500, 0);
final DateTime endTimeDate = endTime.toDate();
final DateTime startTimeDate = startTime.toDate();
final Duration difference = endTimeDate.difference(startTimeDate);

Convert milisecond to date to compare to today's date

I have a set of data stored in neo4j in milliseconds.
I'm trying to get the data then change it to date format and compare it to today's date in where clause to get Media posts for today only.
I have tried with these
MATCH (media:Media)
RETURN date(datetime({millisecond:media.dateCreated}))
and it returns
Neo.ClientError.Statement.ArgumentError: year must be specified
next, I've tried
MATCH (media:Media)
RETURN apoc.date.field(media.dateCreated)
and it returns
Neo.ClientError.Statement.SyntaxError: Unknown function
'apoc.date.field' (line 2, column 28 (offset: 45)) "MATCH
(media:Media) RETURN apoc.date.field(media.dateCreated)" ^
I have tried multiple ways that more or less return the same kind of error
I expect the data to be shown in date format instead of milliseconds.
You can use epochMillis to create the date from milliseconds.
MATCH (media:Media)
RETURN date(datetime({epochMillis:media.dateCreated}))
This returns the date in the format as shown in the following screenshot:
This query:
RETURN datetime({epochMillis: 1475292465000});
returns the datetime that corresponds to the epoch timestamp 1475292465000:
╒════════════════════════════════════════╕
│"datetime({epochMillis: 1475292465000})"│
╞════════════════════════════════════════╡
│"2016-10-01T03:27:45Z" │
└────────────────────────────────────────┘
If you actually want a date, you can use this query:
RETURN date(datetime({epochMillis: 1475292465000}));

mongodb difference in time

How can i filter database entries that have a datetime less than 60min in the past?
I tried some date operations as follows in mongodb with two fields timestamp and marketstartime that are of type date in all my documents:
{"$subtract": ["$timestamp", "$marketstartime"]}
but it returns always null for that operation. Why?
My timestamp and marketstartime entries in the db are in date type and look as follows, this should be correct:
2017-12-23 12:00:00.000Z
The actual question I’m trying to solve: How can I get all entries that have a timestamp less than 60 min in the past from now?
A query can composed for documents with timestamp value set less than 60 minutes ago.
from datetime import datetime, timedelta
query = {
'$timestamp': {
'$lt': datetime.now() + timedelta(minutes=-60)
}
}
cursor = db.collection.find(query)