How to get current timestamp of firebase server in milliseconds?

前端 未结 3 559
[愿得一人]
[愿得一人] 2020-12-15 18:21

I wanted to get firebase current timestamp, not able to find a way to get that. I want to save child as shown in the image. And for that I\'ve to get timestamp and get the d

3条回答
  •  春和景丽
    2020-12-15 18:30

    You can set the server time by using ServerValue.TIMESTAMP which is a Map type with {".sv" : "timestamp"} pair. When it's sent to the firebase database, it will be converted to a Long Unix epoch time like this 1469554720.

    So the problem is, you can't set this as a key directly. The best approach is to put the timestamp inside your object and use DatabaseReference.push() to get the guaranteed unique key.

    For example

    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    String key = ref.push().getKey(); // this will create a new unique key
    Map value = new HashMap<>();
    value.put("name", "shesh");
    value.put("address", "lucknow");
    value.put("timestamp", ServerValue.TIMESTAMP);
    ref.child(key).setValue(value);
    

    If you want to save it with that format (dd-mm-yyyy), there's a hack but this is not recommended. You need to save it first (ServerValue.TIMESTAMP) to another temporary node, and then retrieve the timestamp before convert it into that format using Date class.

提交回复
热议问题