Why passing firestore timestamp to ``moment`` gives the output as invalid date? - google-cloud-firestore

In my project, I am using moment.js. When I pass firestore timestamp to moment it throws the output as invalid date.
Here is my code:
moment({seconds: 1663679594, nanoseconds: 42000000}).format('MM-DD-YYYY')
Please guide me on how to resolve this error.

Firestore stores Dates as a Timestamp object. This is not the same as a Javascript Date() object. You have to convert it first into a Javascript Date object using the .toDate() method that Firestore has provided. See Sample code below:
var db = firebase.firestore();
db
.collection('collection-name')
.doc('document-id')
.get()
.then((doc) => {
const converted = doc.data().timestamp.toDate();
const momentDate = moment(converted).format('MM-DD-YYYY')
console.log(momentDate);
})
For more information, you may check out this documentation.

Related

stop further date conversion which is already in UTC

By default any date/timestamp stored in postgres is in standard UTC. Postgres has the DATE column type that stores only the date part of a full timestamp.
When using typeorm for postgres, and using the repositories the date is fetched as is. Yet, when you do something with a raw query like this:
const queryRunner = await this.connection.createQueryRunner();
await queryRunner.connect()
const response = await queryRunner.query('SELECT * FROM MY_VIEW WHERE AGE=23');
For the same date(only) column I receive something like this, which has its value as '1999-01-02'
{
name: 'mleko',
age : '23',
dob : '1999-01-01:T22:00:00:000Z',
address: 'xyz'
}
I'm not sure where exactly is this conversion taking place, probably the underlying driver that typeorm uses, yet, how do I tell typeorm to not do this conversion for a date already in UTC into again a UTC.
So, the way I got around this was doing a cast on the raw query:
const queryRunner = await this.connection.createQueryRunner();
await queryRunner.connect()
const response = await queryRunner.query('SELECT name, age, dob::VARCHAR, address FROM MY_VIEW WHERE AGE=23');
this would avoid any conversions

Cloud Firestore QuerySnapshot Where function field not supported

I am using Cloud Firebase on my android app and I want to filter my documents using where function to avoid unnecessary billing cost, my problem is instead of using document field inside my where function I prefer model to filter my data due to multiple advantage, then I try below code, but it trough error of
"'field is String || field is FieldPath || field == FieldPath.documentId': Supported [field] types are [String] and [FieldPath].,"
I try this
final authPhoneNo = Utils.formatPhoneNo(phoneNo!);
CollectionReference receiptCollection = FirebaseFirestore.instance
.collection('example');
QuerySnapshot querySnapshot;
querySnapshot = await receiptCollection.orderBy('Date', descending: true).where((e){
Utils.formatPhoneNo(MainData.fromJson(e.data()).userPhoneNo!);
}, isEqualTo: authPhoneNo).get();
formatPhoneNo
static formatPhoneNo(String phoneNo) => phoneNo.replaceAll(RegExp(r"\D"), "")
.substring(
(phoneNo.replaceAll(RegExp(r"\D"), "").length) - 9,
(phoneNo.replaceAll(RegExp(r"\D"), "").length)
);
It through error on where((e)
'field is String || field is FieldPath || field == FieldPath.documentId': Supported [field] types are [String] and [FieldPath].
From the code you provided, I see that you want to filter data using where and a formatter function formatPhoneNo, but this is not how it works according to the official documentation:
// Create a reference to the cities collection
final citiesRef = db.collection("cities");
// Create a query against the collection.
final query = citiesRef.where("state", isEqualTo: "CA");
As you can see, the first parameter on the where clause refers to the field you want to filter and the second one refers to the query operation you want to perform (in this case, isEqualTo) and the reference value (in the example, the string "CA").
In your case, the right way to do the query would be as follows:
querySnapshot = await receiptCollection.where('phoneNo', isEqualTo: authPhoneNo).get();
To avoid the use of a formatter, which leads to unnecessary processing time every time it is called and; in this case could lead to format every result until the desired value matches the condition if its done without the where Firebase function, I would recommend to sanitize your data before saving it to Firebase as recommended in this article:
2. Standardize phone number formatting
When you capture telephone data, either directly from the customer or via an ingress from a data supplier, you should standardize the telephone number format. Ideally, you should use the industry-standard E.164 format
...
If you prefer to display a telephone number in a nice to read human format you can still store the number in your database in E.164 format but present the number on the screen in a friendly format.
Doing this way, you could filter your data saved in Firebase using simple and compound queries as shown in the Firebase documentation.

How to convert and compare dates in spring mongodb data

I am trying to retrieve records from mongodb collection after certain date but the date field is stored as a string in mongodb collection. The below query doesn't work well I guess because it does a string comparison. How can I convert the string date from mongo and then compare with input date.
`mongoOperations.find(query(where("lastUpdated").gte(inputTimeStamp).and("status").in("COMPLETED")), Cart.class);`
Something like this worked for me. This may not be the best way to do it because it has potential of sql injection but I made sure data is sanitized before it reaches here.
String queryStr = "{\"$expr\": {\"$gte\": [{ \"$dateFromString\": { \"dateString\": \"$lastUpdated\",timezone:\"America/New_York\" }}, new Date(\"%s\") ]},status:{$in:[\"COMPLETED\"]}}";
BasicQuery query = new BasicQuery(String.format(queryStr,timeStamp));
return mongoTemplate.find(query, Cart.class);

Change input Date format? Vuejs + mongoose

Problem: Change the Date input field from "mm/dd/yyyy" to "dd/mm/yyyy".
I already know how to change after i receive the date, but the problem is that when the client is typing the input is still receiving "mm/dd/yyyy".
My mongoose schema:
const schemaRegister = new mongoose.Schema({
date: Date,
});
My input area:
<b-form-input v-mask="'##/##/####'" v-model="date"></b-form-input>
My date formating (using momentsjs):
changeDateFormat() {
let fixedDate = moment(this.registers[i].date).format("L");
this.registers[i].date = fixedDate;
}
I am displaying the 'fixedDate' on the table, but it doesn't help a lot because when the client is typing he thinks the first 2 slots are the days (dd), but in reality they are the month (mm). As a solution i thought of using the Date as a String but then it would make the verification very difficult.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
just pass the parameters in the correct order, like this:
new Date(day, monthIndex, year);
I wasn't using the 'momentsjs' correctly, first i needed to parse the input date by using
let formatedDate = moment(this.date,"DD-MM-YYYY");
and then for displaying the date i should have used
let fixedDate = moment(this.registers.date).format("DD/MM/YYYY");

How to add a timestamp to my array/List in firestore?

I wish to generate a scatter plot using time on the x-axis from user generated submissions. To do so I am making a list of maps in which each map is the user submission and contains a timestamp field. The issue is that I cannot add a timestamp using the arrayUnion. This issue was mentioned in this post:
Link1
You can't use FieldValue.serverTimestamp() as the value to union (add) or >remove, to or from, an array type value of a document field. If you want to >use that timestamp value, you need to pass it directly to a field you're >updating or setting.
So,to solve my problem I need to update directly the field for timestamp after I have already added some data which has a form similar to below and I only need to add to the last element/Map of my List/array of Maps but I do not know how long this list currently is:
myList[{Map1}{Map2}{Map3}...{examplefield:'Some data', timstamp:null}]
final Map submissionMap = submissionData.toMap();
//Running a firestore transaction...
final DocumentReference areaDocument = Firestore.instance.document('Space/SAJJEED');
Firestore.instance.runTransaction((Transaction tx) async {
DocumentSnapshot postSnapshot = await tx.get(areaDocument);
if (postSnapshot.exists) {
//Adds the data except for the timestamp needed
await tx.update(areaDocument, <String, dynamic>{'$status': FieldValue.arrayUnion([submissionMap])});
//Insert Code for directly accessing the timestamp field and adding Timestamp
}
});```
Any other workarounds would be appreciated as well.