skip to Main Content

While we serialize or de-serialize the model using jsonSerializable in Flutter it converts the DateTime as String

class Task {
 final DateTime dateTime;
 final String taskName;

 Task({
  required this.dateTime,
  required this.taskName
 }):
}

Instead of converting as string it should convert as TimeStamp

3

Answers


  1. Chosen as BEST ANSWER
    1. We can annotate the field with @TimeStampConverter
    class Task {
     @TimeStampConvertor
     final DateTime dateTime;
     final String taskName;
    
     Task({
      required this.dateTime,
      required this.taskName
     }):
    }
    
    1. Create a class for TimeStampConverter
    class TimestampConverter implements JsonConverter<DateTime, Timestamp> {
      const TimestampConverter();
    
      @override
      DateTime fromJson(Timestamp timestamp) {
        return timestamp.toDate();
      }
    
      @override
      Timestamp toJson(DateTime date) => Timestamp.fromDate(date);
    }
    

  2. Try with this:

    import 'package:cloud_firestore/cloud_firestore.dart';
    
    // For Converting Firebase Timestamp to DateTime
     
     //From Firebase field to Dart Timestamp
     Timestamp _timestamp = doc['dateTime'];
     
     //From Timestamp to Dart DateTime
     DateTime date = _timestamp.toDate();
    
     //From Dart DateTime to Timestamp
      Timestamp _timestamp =
              Timestamp.fromDate(DateTime.now());
    
    
    Login or Signup to reply.
  3. Use @JsonKey. This is a sample from json_serializable :

     @JsonSerializable()
     class Sample3 {
       Sample3(this.value);
    
       factory Sample3.fromJson(Map<String, dynamic> json) =>
           _$Sample3FromJson(json);
    
       @JsonKey(
         toJson: _toJson,
         fromJson: _fromJson,
       )
       final DateTime value;
    
       Map<String, dynamic> toJson() => _$Sample3ToJson(this);
    
       static int _toJson(DateTime value) => value.millisecondsSinceEpoch;
       static DateTime _fromJson(int value) =>
           DateTime.fromMillisecondsSinceEpoch(value);
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search