Comparing calendar datetime to yyyy-mm-dd format in flutter - 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

Related

DateRangePicker - Grey out unavailable dates

As the title suggests I am using DateRangePicker to add date ranges to an array. If possible I would like to be able to "grey" out already selected dates in the array. Is there anyway to do this?
Here is the solution to returning the dates in-between the range in case anyone else needs it.
List<DateTime> getDaysInBetweenIncludingStartEndDate(
{required DateTime startDateTime, required DateTime endDateTime}) {
// Converting dates provided to UTC
// So that all things like DST don't affect subtraction and addition on dates
DateTime startDateInUTC =
DateTime.utc(startDateTime.year, startDateTime.month, startDateTime.day);
DateTime endDateInUTC =
DateTime.utc(endDateTime.year, endDateTime.month, endDateTime.day);
// Created a list to hold all dates
List<DateTime> daysInFormat = [];
// Starting a loop with the initial value as the Start Date
// With an increment of 1 day on each loop
// With condition current value of loop is smaller than or same as end date
for (DateTime i = startDateInUTC;
i.isBefore(endDateInUTC) || i.isAtSameMomentAs(endDateInUTC);
i = i.add(const Duration(days: 1))) {
// Converting back UTC date to Local date if it was local before
// Or keeping in UTC format if it was UTC
if (startDateTime.isUtc) {
daysInFormat.add(i);
} else {
daysInFormat.add(DateTime(i.year, i.month, i.day));
}
}
return daysInFormat;
}
Yes, you can send disabled dates into the component.
Check this sample of the documentation.
For further options, check the whole docs.

Convert milliseconds to Firestore date

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".

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?

Formatting Timestamp from Cloud Firestore to Date in Flutter

I have 2 fields: created_at and updated_at field in my DB on Cloud Firestore. They are of type Timestamp.
In my Model, I have also created the respective fields like so
class User {
String id;
String firstName;
String lastName;
Timestamp created_at;
Timestamp updated_at;
}
I have the respective fromMap and toMap functions in my models. In my view user screen, how do I format my created_at and updated_at fields and display them in Text widgets as 8 May, 2020?
Thanks.
You can convert a Timestamp to a Date like so:
DateTime date = created_at.toDate();
And if you want to display it as a text you can convert your date like this:
String dateString = DateFormat('dd MMM, yyyy').foramt(date);
Therefore you need the intl Package: https://pub.dev/packages/intl

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;
}