0

Trying to convert Firestore Timestamp to DateTime in Flutter I'm getting always an error, tried all of the solutions, none worked ( last tried How to print Firestore timestamp as formatted date and time)

Here's my code below;

Code

factory UserModel.fromMap(Map<String, dynamic> map) {
    return UserModel(
      name: map['name'],
      email: map['email'],
      username: map['username'],
      registerDate:
          DateTime.fromMillisecondsSinceEpoch(map['registerDate'] * 1000),
      id: map['id'],
      imageUrl: map['imageUrl'],
      cvUrl: map['cvUrl'],
      phoneNumber: map['phoneNumber'],
      education: Education.fromMap(map['education']),
      location: Location.fromMap(map['location']),
      lookingForIntern: map['lookingForIntern'],
    );
  }

Error

'Timestamp' has no instance method '*'.
Receiver: Instance of 'Timestamp'

Converted DateTime to Timestamp, and changed

registerDate:
              DateTime.fromMillisecondsSinceEpoch(map['registerDate'] * 1000),

to

registerDate:map['registerDate']

now getting error below;

Converting object to an encodable object failed: Instance of 'Timestamp'

but print(map['registerDate']) prints Timestamp(seconds=1632412800, nanoseconds=0)

Emir Kutlugün
  • 127
  • 1
  • 14
  • This bug seems out there for a long time, The solution would be having the TimeStamp in model instead of the DateTime. – EngineSense Sep 24 '21 at 06:51
  • @EngineSense Can you please check the [following thread](https://stackoverflow.com/questions/50632217/dart-flutter-converting-timestamp) if it answers your question? – Rajeev Tirumalasetty Sep 24 '21 at 15:26
  • 1
    nope, not related to the issue! thanks – EngineSense Sep 25 '21 at 05:29
  • Does this answer your question? [How do I convert a Firestore Timestamp to a Dart DateTime](https://stackoverflow.com/questions/57153562/how-do-i-convert-a-firestore-timestamp-to-a-dart-datetime) – Rajeev Tirumalasetty Oct 13 '21 at 11:48
  • I switched my DateTime variable to 'dynamic' then converted it to DateTime in my UI using https://pub.dev/packages/date_format this package. But no, you can't convert Timestamp to DateTime directly, really annoying. – Emir Kutlugün Oct 20 '21 at 10:57

1 Answers1

0

Try this package to handle the problem-

https://pub.dev/packages/date_format

import 'package:date_format/date_format.dart';


     DateTime datetime = stamp.toDate();
        var time = formatDate(datetime, [hh, ':', nn, ' ', am]);
Dharman
  • 26,923
  • 21
  • 73
  • 125
Vishal_VE
  • 1,249
  • 1
  • 1
  • 8