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

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

Related

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

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());

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?

Invalid Date Format - Flutter/Dart

It might be a simple solution but I have some problems with it. I have JSON response with user data like name, address, and birthday. However, birthDay is empty and I cannot parse it.
Error (only those lines occure):
Exception has occurred.
FormatException (FormatException: Invalid date format
)
I'm using tryParse and DateFormatter with null check but it seems to not work as I expect. Below you'll find part of code and JSON response:
Part of response:
birthDay: "" // as you see it's empty
bioInfo: ""
badges: List(6 items)
agreement5: false
Part of Profile Entity:
class ProfileEntity {
final String birthDay;
ProfileEntity.fromJson(Map<String, dynamic> json)
: birthDay = json['birthDay'],
}
Part of Profile Model:
class ProfileModel {
final DateTime birthDate;
ProfileModel({#required this.birthDate});
ProfileModel.fromEntities(
ProfileEntity profileEntity,
) : birthDate = DateTime.tryParse(profileEntity.birthDay), //place where I'm getting an error - value is null in this case.
//here I'm sending it to form field
Map<String, String> toFormFields() {
return {
'jform[birthDay]':
birthDate != null ? DateFormat("yyyy-MM-dd").format(birthDate) : "", //null check
}
}
}
Do you have any idea how to get rid of this? (Error message do not provide any info despite what I paste above in error part)
DateTime.tryParse does not expect null value.
You can replace this with DateTime.tryParse(profileEntity.birthDay ?? '') which will return null instead of throwing exception.
For ref: tryParse method
DateFormat('dd-MM-yyyy').parse(widget.initialDate);
remember you can change date format according to which you api sends date in my case 'dd-MM-yyy' in your case may be different format.

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

Apollo/GraphQL: Field Type to Use for Timestamp?

I'm storing a value to a postgres field that is of type timestamp with time zone. I was defining the field as an int in my Apollo schema, but I'm getting this error message in the resolver:
column "apptDateTime" is of type timestamp with time zone but expression is of type integer
Looking up GraphQL data types, I don't yet see any type that is cited as corresponding to a field of type timestamp.
What's the correct field type to use in the Apollo schema for a field that is of type timestamp in the database?
I find this way to work with input in forms, needed convert from client (input form) to the server, and from the server to client (input form)
Graphql:
updatedAt: String
Sequelize:
updatedAt: { type: Sequelize.DATE },
Postgresql:
"createdAt" timestamp(6) with time zone DEFAULT now(),
Value transform to the Server:
value = dateToISO(value);
Value transform to the Client:
if ( isNil(value) ) {
value = '';
} else {
value = value.toLocaleDateString() +' '+ value.toLocaleTimeString();
}
the helpers:
let dateToISO = function (dateString) {
if (!dateString) {
return null;
}
let p = dateString.split(/\D/g);
/* It's up your date on input in this case come from DD-MM-YYYY
for MM-DD-YYY use: return [p[1], p[2], p[0]].join('-'); */
return [p[2], p[1], p[0]].join('-');
};
I got my mutation working that includes a field of type Timestamp with Time Zone. I did it by changing the schema for my apptDateTime field from Int to String, and passing in an ISO string. Sequelize and Postgres took care of changing it into a field of type Timestamp with Time Zone.
Update 2021:
Here's what I'm using these days.
Sequelize:
timeOfNonce: {type: Sequelize.DATE}
Schema:
scalar DATETIME
.....
timeOfNonce: DATETIME
These days I let Sequelize define my SQL tables via:
const deleteAllData_fromThisModel = false;
const alterThisTableToMatchDBConnectorsModel = true;
myDataModel.sync({force: deleteAllData_fromThisModel,
alter: alterThisTableToMatchDBConnectorsModel}).then(err => {
console.log('myDataModel has been synced')
}).catch(err => {
throw err
});