user7773428
user7773428

Reputation:

How to convert firebase timestamp into date and time as Date is deprecated

How do i convert ServerValue.TIMESTAMP into SimpleDateFormat("dd MM yyyy") Date is deprecated so not able to use it , is their is any way to use calender

Upvotes: 0

Views: 7552

Answers (2)

Sunshinator
Sunshinator

Reputation: 950

You cannot use Server.TIMESTAMP to get a date. The doc says:

A placeholder value for auto-populating the current timestamp (time since the Unix epoch, in milliseconds) as determined by the Firebase servers

This means that when you setValue() or updateChildren(), you can put this constant in the Map to tell the server to put the epoch time in that node instead. For example:

mRef = FirebaseDatabase.getInstance().child("whatever/path/in/your/database");
mRef.setValue( Server.TIMESTAMP );

This will set in <your Firebase>/whatever/path/in/your/database a long that will look like 149141530600. This is the current epoch time I fetched while writing this answer. It corresponds to the number of milliseconds passed since january 1st 1970 to when I copied the value. Then, if you have a listener to that node, you can get the calendar using:

Long time = dataSnapshot.getValue(Long.class);
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTimeInMillis(time);

If you only want the time the server is set to (saving it in the database is pointless), you can use the special node:

`FirebaseDatabase.getInstance().getReference(".info/serverTimeOffset");`

A listener to this node returns a Double that represents an approximative offset between the device time and the server time. You can then set the Calendar using:

calendar.setTimeInMillis(System.currentTimeMillis() + offset);

Upvotes: 1

Chris - Jr
Chris - Jr

Reputation: 397

You can use the following.

Calendar cal = Calendar.getInstance();

cal.setTimeInMillis(ServerValue.TIMESTAMP);
SimpleDateFormat fmt = new SimpleDateFormat("dd MM yyyy",Locale.US);
fmt.format(cal.getTime()); //This returns a string formatted in the above way.

If ServerValue.TIMESTAMP is returned as a string, you can parse the string using Long.parseLong(Server.TIMESTAMP);

Upvotes: 0

Related Questions