Convert milliseconds to Firestore date - flutter

In Flutter I convert dates to milliseconds like this:
static DateTime createDateTimeNow() {
return DateTime(DateTime.now().year, DateTime.now().month,
DateTime.now().day, 0, 0, 0, 0, 0);
}
// This create a number value like 1660341600000
final Number millisecondsNow = Helpers.createDateTimeNow().toUtc().millisecondsSinceEpoch;
// I can also format is as String to be presented based on the language
final String dateNow = DateFormat.yMMMMd(language).format(millisecondsNow);
Now I have Firebase Cloud Functions that should read these dates and send notification when they expire, but could I convert this number to a normal date in Firestore?
From Flutter I do something like this:
final DateTime dateNow = DateTime.fromMillisecondsSinceEpoch(1660341600000);

You can use fromMillis( ) method from firestore.timestamp which can create new timestamp from the given number of milliseconds.
firestore.Timestamp.fromMillis(milliseconds)
You can refer these documents for more details firestore timestamp from milliseconds and Firestore Timestamp

You're working too hard. Firestore Timestamp to Dart DateTime:
final dt = aTimestamp.toDate();
and from DateTime to Timestamp:
final ts = Timestamp.fromDate(aDt);
as described in https://pub.dev/documentation/cloud_firestore_platform_interface/latest/cloud_firestore_platform_interface/Timestamp-class.html
and there's no need to think about "milliseconds".

Related

I couldn't insert data to firestore on flutter

I couldn't insert the duration in firestore on flutter. In 'field6'. type of data from firestore should match with field6 .How to do that?
'field5' inserting correctly
enter image description here
CODE
duration calculating method
DateDuration? duration;
void calAge() {
DateTime? birthday = selectedDate;
duration = AgeCalculator.age(birthday!);
print('Your age is $duration');
}
inset firestore
void send() {
FirebaseFirestore.instance.collection("data").doc().set({
"field5": selectedDate,
"field6": Duration(duration).toString(),
});
}
enter image description here
Saving dates in firestore can be tricky if you need to save the current datetime you need to use FieldValue.serverTimestamp() provided by firebase but if you need to be more dynamic, you can save it as a string then when getting it back from firestore you will use DateTime.parse(your string date) also you can save it as an int and when getting it you use DateTime.fromMicrosecondsSinceEpoch(your int date) if your time stamp is in micro seconds but use this if its in seconds DateTime.fromMillisecondsSinceEpoch(your int date)

how to convert a time eg- 22:00:00 to a timestamp + include next day date in Flutter

I want to ask how to convert a given time for example 22:00:00 into a timestamp and also add the next day date to it while converting into a time stamp in flutter.
Thank You
You can convert a Date string to a timestamp
convertDateTimeToTimestamp(String yourDateTime, [Duration? extraDuration]) {
DateTime date = DateTime.parse(yourDateTime);
if (extraDuration != null) {
date = date.add(extraDuration);
}
return date.microsecondsSinceEpoch;
}
then your example with one additional day (next day) can be:
main() {
final timestamp = convertDateTimeToTimestamp(
"2022-03-05 22:00:00",
Duration(days: 1),
);
print(timestamp); //output: 1646600400000000
// try to check the converted timestamp with addition duration in the example above, it's only one day
DateTime date = DateTime.fromMicrosecondsSinceEpoch(timestamp);
print('${date.year}-${date.month}-${date.day} ${date.hour}:${date.minute}:${date.second}'); //output: 2022-3-6 22:0:0
}
you can use intl package and format your datetime easier.
Timestamp data type is defined in cloud_firestore.
What do you mean by timestamp?

Comparing calendar datetime to yyyy-mm-dd format in flutter

I have a calendar and in the calendar events are added in here
Map<DateTime, List<EventStore>> get events => _events;
where EventStore is anotherClass like this,
class EventStore{
String subject;
String level;
String room;
EventStore({this.subject,this.level,this.room});
}
Now, I want to compare today's date in yyyy-mm-dd format with the calendar date format. And I also don't know how to see the calendar date format.
How do I compare today's date in yyyy-mm-dd format with the calendar date format? So that I can show all the events that are on the particular date anywhere in my app?
And can anybody say, what is the DateTime format in map,
Map<DateTime, List<EventStore>> get events => _events;
DateTime objects don't contain a date format, it's technically a number of elapsed time since 01-01-1970 https://api.flutter.dev/flutter/dart-core/DateTime-class.html
You can compare DateTime objects using their attributes.
DateTime savedDateTime = getSavedDateFromServer();
DateTime now = DateTime.now();
bool isSameYear = savedDateTime.year == now.year;
bool isSameMonth = savedDateTime.month == now.month;
//etc.
If you want to group your objects by date I recommend you take a look at this:
Flutter/Dart how to groupBy list of maps

Flutter Firstore Timestamp now / current date

Below are all the Firebase timestamp methods that I have used and found handy.
How to get a Firestore timestamp (Todays date)
Timestamp timestampDate = Timestamp.now();
How to set a Timestamp from Datetime
DateTime someDate = DateTime.now();
Timestamp timestampDate = Timestamp.fromDate(DateTime(someDate.year, someDate.month, someDate.day))
How to get the Date object from Timestamp
DateTime dateTime = timestampDate.toDate();

Timestamp to LocalDateTime conversion

I am reading a date from Firestore which is of type Timestamp and I want it converted as a LocalDateTime type.
To do so, I used the following procedure:
Convert the Timestamp to a DateTime
Use the .dateTime method of LocalDateTime to convert it to a LocalDateTime
Manually adjust it to my local time
LocalDateTime.dateTime(entity.start.toDate()).addHours(2),
Although entity.start.toDate() has my local time the .dateTime does some adjustments and I get some other time.
Also, this method is prone to errors sinve I am adjusting something manually.
Another way to do so would be the following but I find it too long:
DateTime hStartDate = entity.start.toDate();
LocalDateTime(hStartDate.year,hStartDate.month,hStartDate.day,hStartDate.hour,hStartDate.minute,0)
Any suggestions?
I had a similar issues I wasnt able to find a way to convert Timestamp String to Timestamp object again.
So i used this way out.
When you save data to firestore:
Use -
DateTime.now().toString()
Example :
await Firestore.instance
.collection("users/$docId/tokens")
.document(fcm.deviceToken)
.setData({
"token": fcm.deviceToken,
"timestamp": DateTime.now().toString()
});
When u get data from firestore and get the timestamp string:
Use this to get DateTime object -
DateTime dateTime = DateTime.parse(timestamp)
Use this to get TimeOfDay object -
TimeOfDay timeOfDay = TimeOfDay.fromDateTime(dateTime);
timeOfDay.format(context);
You can achieve this by using toLocal ( ) method.
something like this.
_getDate(//timestamp, "yyyy.dd.MM, HH:mm");
String _getDate(int timestamp, String dateFormat) {
DateTime date = DateTime.fromMillisecondsSinceEpoch(
timestamp * 1000,
).toLocal();
String formattedDateTime = DateFormat(dateFormat).format(date);
return formattedDateTime;
}