Get current Date and Time using Firebase Cloud functions

Viewed 6161

I'm pretty much new to Firebase Cloud Functions, so I don't know whether the question I'm going to ask is valid/not.

So basically I'm working on an android fantasy game (which uses firebase database) which has several contests to be started and ended based on the contest's date and time validity. So I want to get the current date and time so that I can calculate the time remaining to participate in the contest and save that in the database (using CLoud functions)

So to get the current time, should I use APIs like 'https://timezonedb.com/api' or is there anything else I can do to get the time.

Also, how can I calculate the remaining time given the deadline and the current time (in TypeScript language)?

I went through a lot of videos and docs, but couldn't figure out any approach. A short explanation and some useful links would be of great help.

2 Answers

With code running in Cloud Functions, you can trust that the server's sense of time is accurate. For JavaScript running in a node environment, simply run Date.now() to return a timestamp in milliseconds since unix epoch. There is nothing more to do.

You can get the current time from the Firebase by using ServerValue.TIMESTAMP without the need to use Cloud Functions since you have already use Realtime db.

Example code snippet:

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);
Related