EngineSense
EngineSense

Reputation: 3616

TimeStamp to DateTime conversion Firebase to Flutter

Straight to the issue. I am new to Firebase Firestore.

I have model:


     @JsonSerializable()
      class CategoryEntity extends Equatable {
       final String id;
       final String name;
       @JsonKey(fromJson: _fromJson, toJson: _toJson)
       final DateTime createdDate;
       @JsonKey(fromJson: _fromJson, toJson: _toJson)
       final DateTime updatedDate; 
       final String description;

    const CategoryEntity(
      this.id,
      this.name,
      this.createdDate,
      this.updatedDate,
      this.description,
    );

The data that is to be saved in Firebase Firestore is Timestamp for createDate and updatedDate.

But the problem is that I cannot convert the data from Firebase to local. The save method converts the dateCreate to Timestamp fine.

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

Any solution please.

Upvotes: 2

Views: 1077

Answers (1)

Abel Mekonnen
Abel Mekonnen

Reputation: 1915

From my understanding, you want to show the ServerTimeStamp to the user local time.

I have two ways you can check,

One using this package timeformatter, will show you the time according to the users time.

A mini truth table for the format of the value returned by the function:
< 1 second : "Just now"
< 60 seconds : "X seconds" (2-59)
< 2 minutes : "1 minute"
< 60 minutes : "X minutes" (2-59)
< 2 hours : "1 hour"
< 24 hours : "X hours" (2-23)
< 2 days : "1 day"
< 7 days : "X days" (2-6)
< 2 weeks : "1 week"
< 28 days : "X weeks" (2-3)
< 30.44 * 1.5 days : "1 month"
< 365 - 15.22 days : "X months" (2-12)
< 730 days : "1 year"
Rest: "X years"

Two, you can use this package to change it intl

import 'package:intl/intl.dart';

int timeInMillis = 1586348737122; //no need to convert it just set the timestamp here.
var date = DateTime.fromMillisecondsSinceEpoch(timeInMillis);
var formattedDate = DateFormat.yMMMd().format(date); //

you can see the answer on this post for more info Dart/Flutter : Converting timestamp

Upvotes: 1

Related Questions