android – How to get current timestamp of firebase server in milliseconds?-ThrowExceptions

Exception or error:

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 date accordingly. Please help…

here is the result I want to get

How to solve:

You can set the server time by using ServerValue.TIMESTAMP which is a Map<String, String> 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<String, Object> 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.

###

Actually, you can use cloud functions, and get the timestamp via an HTTP request.
The function is very simple.

exports.getTimeStamp = functions.https.onRequest((req, res)=>{
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify({ timestamp: Date.now() }));
});

###

On Android I did it this way

index.js / serverside

const functions = require('firebase-functions'); 
exports.stamp = functions.https.onCall(() => {
       var d = new Date();
       console.log('TimeStamp_now : '+d.getTime());
       return { timeStamp: d.getTime() };          
   });

someclass.kt / clientside

lateinit var functions: FirebaseFunctions
var ret :Long = 0

FirebaseApp.initializeApp(this)
functions = FirebaseFunctions.getInstance()


val returnFC = functions.getHttpsCallable("stamp").call()
    returnFC.continueWith { task ->
    val resultFC = task.result?.data as Map<String, Any>
        resultFC["timeStamp"] as Long
    ret = "${resultFC["timeStamp"]}".toLong()
    val cal = Calendar.getInstance()
        cal.timeInMillis = "$ret".toLong()
    var date = DateFormat.format("dd-MM-yyyy", cal).toString()
    Log.d("current date:", date)
    Log.d("timeStamp_from_function :", "$ret")
    resultFC
}
    returnFC.addOnSuccessListener {
        Log.d("OnSuccessListener :", "success")
}    
    returnFC.addOnFailureListener {
        Log.d("OnFailureListener:", "failure")
}

I got the return and arrived at: TimestampConvert look great

Leave a Reply

Your email address will not be published. Required fields are marked *