Home > Mobile >  How can I format timeStamp date that gets from FBfirestore
How can I format timeStamp date that gets from FBfirestore

Time:08-01

I am having problem with the timeStamp on getting the data on the FBfirestore If you knows that’s there’s anyways that format the date Please help Thanks.

Code: (What I get so far)

 StreamBuilder<DocumentSnapshot?>(
      stream: FirebaseFirestore.instance
          .collection("users")
          .doc(userUid)
          .snapshots(),
      builder: (context, snapshot) {
        if (snapshot.data == null) {
          return const Text(
              'Oops sometings went wrong.\n *Please exist the app*');
        }
    return Center(
     child: Text((snapshot.data as DocumentSnapshot)['accountCreated'].toString()
     ),
    ),

I want to get exactly this timeStamp: enter image description here

But this is what I get instead: enter image description here Create the user on the FBfirestore:

Future<String> createUser(UserModel 
   user) async {
   String retVal = "error";
    try {
      await  
                                                        
  _firestore.collection("users").doc(user.uid) 
      .set({
      'accountCreated': Timestamp.now(),
      'email': user.email,
      'fullName': user.fullName,
      'provider': user.provider,
      'groupId': user.groupId,
      'groupLeader': user.groupLeader,
      'groupName': user.groupName,
    });
    retVal;
    "success";
  } catch (e) {
    // ignore: avoid_print
    print(e);
  }
  return retVal;
}

CodePudding user response:

The timestamp object in the firestore database is a firestore object which you can then call toDate() https://pub.dev/documentation/cloud_firestore_platform_interface/latest/cloud_firestore_platform_interface/Timestamp-class.html on to convert it to a dart/flutter date object. You can then use flutters built in formatting tool to convert the date to something text readable. https://api.flutter.dev/flutter/intl/DateFormat-class.html

The formatting of that timestamp would look something like this : DateFormat.yMd().add_jm()

CodePudding user response:

Please used FieldValue.serverTimestamp() provide by firebase firestore here's the example of your code

  Future<String> createUser(UserModel 
  user) async {
  String retVal = "error";
  try {
  await  
                                                    
_firestore.collection("users").doc(user.uid) 
   .set({
  'accountCreated': FieldValue.serverTimestamp(),
  'email': user.email,
  'fullName': user.fullName,
  'provider': user.provider,
  'groupId': user.groupId,
  'groupLeader': user.groupLeader,
  'groupName': user.groupName,
});
retVal;
"success";
} catch (e) {
// ignore: avoid_print
print(e);
 }
return retVal;

}

  • Related