7

How can I convert an integer timestamp to Datetime.

Sample Code:

@JsonSerializable(nullable: false)
class Person {
  final String firstName;
  final String lastName;
  final DateTime dateOfBirth;
  Person({this.firstName, this.lastName, this.dateOfBirth});
  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
  Map<String, dynamic> toJson() => _$PersonToJson(this);    
}  

How do I convert dateOfBirth integer timeStamp to DateTime?

2 Answers 2

23

To convert an int timestamp to DateTime, you need to pass a static method that returns a DateTime result to the fromJson parameter in the @JsonKey annotation.

This code solves the problem and allows the convertion.

@JsonSerializable(nullable: false)
    class Person {
      final String firstName;
      final String lastName;
      @JsonKey(fromJson: _fromJson, toJson: _toJson)
      final DateTime dateOfBirth;
      Person({this.firstName, this.lastName, this.dateOfBirth});
      factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
      Map<String, dynamic> toJson() => _$PersonToJson(this);

      static DateTime _fromJson(int int) => DateTime.fromMillisecondsSinceEpoch(int);
      static int _toJson(DateTime time) => time.millisecondsSinceEpoch;

    }   

usage

Person person = Person.fromJson(json.decode('{"firstName":"Ada", "lastName":"Amaka", "dateOfBirth": 1553456553132 }'));
Sign up to request clarification or add additional context in comments.

1 Comment

It didn't work for me in my case data from firebase, Has the timestamp value to datetime(local) failed.
10

I use this:

@JsonSerializable()
class Person {
  @JsonKey(fromJson: dateTimeFromTimestamp)
  DateTime dateOfBirth;
 
  ...
}

DateTime dateTimeFromTimestamp(Timestamp timestamp) {
  return timestamp == null ? null : timestamp.toDate();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.