in flutter, i have
var date = DateTime.now().toUtc();
to print it out in string it shows like this (2023-07-12 09:41:03.048759Z)
which create a datetime object with current UTC time.
I need to insert this var date into mongodb timeseries collection which expecting a Date object instead.
The inserting always failed as the format is not right?
Anyone has a solution for this??
Hi @Shuai_Aaron_Shaw,
Welcome to the MongoDB Community!
Could you confirm whether you are using Realm Flutter SDK or something else?
Could you please provide the code snippet where you are trying to insert the date
variable into the MongoDB time-series collection? Additionally, could you share the error message you are encountering? Also, let us know the MongoDB version you are using.
Look forward to hearing from you.
Regards,
Kushagra
hey thanks for the reply, im not using realm flutter sdk, im posting data directly from flutter to mongodb atlas data api, error is timestamp date field is not correct, i have no issues inserting timestamp as utc string to a non-timeseries collection
Hey @Shuai_Aaron_Shaw,
Apologies for the late response.
It seems like the date string is missing a “T” separator between the date and time portions. MongoDB expects dates in ISO-8601 format with a distinct separator.
A couple of ways you can consider fixing the date formatting before inserting:
- Format as ISO string with “T” separator
- Convert string to Date object
- Use
ISODate()
helper. To read more refer to Date()
- MongoDB Docs
I came across the “toIso8601String” method in the DateTime class in Dart’s API documentation. This method might be helpful to you.
In case you need further help please share the code snippet that you are using to post the data in the TS collection, as well as the exact error message you are encountering. This information will help us assist you more effectively.
Regards,
Kushagra