Flutter type 'String' is not a subtype of type 'DateTime' in type cast [duplicate] - flutter

This question already has answers here:
Flutter: Invalid date format 24-09-2022
(3 answers)
Closed 5 months ago.
I am trying to compare date and asper date i am doing some actioin, but I am getting following error.
"type 'String' is not a subtype of type 'DateTime' in type cast"
I am getting date from API in this format 25-09-2022
var postList have all data from api(in this case i am getting start and end date from API)
following are my code:-
DateTime stdt = DateFormat('dd-MM-yyyy').parse(postList.startDate.toString());
DateTime endt = DateFormat('dd-MM-yyyy').parse(postList.endDate.toString());
DateTime crdt = DateFormat('dd-MM-yyyy').format(DateTime.now()) as DateTime;
if (stdt.isAtSameMomentAs(endt)){
if(stdt.isBefore(crdt)){
setState(() {
ComparisonText = "Past";
ContainerColor = Colors.red;
});
}
enter image description here

you are trying to compare string to date time in this line
if(stdt.isBefore(crdt))
try add .toString() like that
DateTime crdt = DateFormat('dd-MM-yyyy').format(DateTime.now().toSring());

Related

_CastError (type 'String' is not a subtype of type 'DateTime' in type cast)

I am trying to add a Date (yyyy/mm/dd) to Firebase and when converting the _selectedDate to a yMd format I am getting this error somnewhere else in my code _CastError (type 'String' is not a subtype of type 'DateTime' in type cast)
Declare variable:
String _selectedDate = DateFormat("yyyy/mm/dd").format(DateTime.now()).toString();
The place where you can enter the date:
MyInputField(
title: "Date",
hint: DateFormat.yMd().format(_selectedDate))
I guess hint requires String and already you converted DateTime.now() to String. So, you may not be allowed to call format for _selectedDate.
MyInputField(
title: "Date",
hint: _selectedDate)
or in assignment
DateTime _selectedTime = DateTime.now();
You are supposed to user either a way, not both.

How to get a certain date in Flutter [duplicate]

This question already has answers here:
Add/Subtract months/years to date in dart?
(11 answers)
Closed 3 months ago.
I am trying to get the current day then getting the day before it, how can I get that date then convert it into a String?
DateTime now = new DateTime.now();
You can do this by doing:
DateTime.now().subtract(Duration(days:1))
Source: https://api.flutter.dev/flutter/dart-core/DateTime-class.html
You can do this :
DateTime now = DateTime.now();
DateTime nowMinus1Day = now. subtract(const Duration(days: 1));
print(nowMinus1Day.toIso8601String());
you can try this
var now = DateTime.now();
var startDate= now.subtract(Duration(days: 1));
print(startDate);

flutter dart datetime in list<map> occur error

my code is below. I want it to be type-recognized as a datetime type at compile time.
var myList = [{
'message': 'foo',
'time': DateTime.now()
}];
DateTime.now().difference(myList[0]['time']);
and it has error of The argument type 'Object?' can't be assigned to the parameter type 'DateTime'.
how can i fix this?
You need to add a type cast for this with the as keyword:
DateTime.now().difference(myList[0]['time'] as DateTime)

Flutter: type 'DateTime' is not a subtype of type 'String'

Text(
DateTime.parse(documents[index]['createdAt']
.toDate()
.toString()) ??
'default',
)
I am trying to get date from firestore. I have DateTime.now() stored in createdIn in firestore.
because the format of both is not the same.
step 1: you can create DateFormat.
step 2: use 'DateFormat'.parse().
try reading this: https://help.talend.com/r/6K8Ti_j8LkR03kjthAW6fg/atMe2rRCZqDW_Xjxy2Wbqg
Here, it is expecting type as 'String', but we are passing it as a 'DateTime' which is incorrect.
Formatting dates in the default 'en_US' format does not require any initialization.
https://api.flutter.dev/flutter/intl/DateFormat-class.html
So, we simply need to format it like:
var dateTime = DateTime.now()
DateFormat.E().format(dateTime)
E() is the constructor of DateFormat in Flutter which refers to first 3 letter of the week
You can refer the official doc for available constructors:
https://api.flutter.dev/flutter/intl/DateFormat-class.html#constructors
Note:
Below is the version used for DateTime library ~ intl
intl: ^0.18.0
(https://pub.dev/packages/intl)
If it's a Timestamp field, cast it to Timestamp. If you need that as a DateTime, use a .toDate on that. Don't process it through a string... completely unnecessary.
It might help you
String? changeDateFormatWithInput(String? currentDate, currentFormat,
requiredFormat) {
String? date;
try {
if (currentDate != null && currentDate.isNotEmpty) {
DateTime tempDate =
new DateFormat(currentFormat).parse(currentDate, true);
date = DateFormat(requiredFormat).format(tempDate.toLocal());
return date;
}
} catch (e) {
print(e);
return null;
}
return date;
}

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