如何在不推荐使用Date时将firebase时间戳转换为日期和时间

时间:2017-04-05 17:29:45

标签: android firebase

如何将ServerValue.TIMESTAMP转换为SimpleDateFormat(“dd MM yyyy”) 日期已弃用,因此无法使用它,是否可以使用日历

2 个答案:

答案 0 :(得分:1)

您无法使用Server.TIMESTAMP来获取约会。医生说:

  

用于自动填充由Firebase服务器确定的当前时间戳(自Unix纪元以来的时间,以毫秒为单位)的占位符值

这意味着当您setValue()updateChildren()时,您可以将此常量放在Map中,以告知服务器将纪元时间放在该节点中。例如:

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

这将在<your Firebase>/whatever/path/in/your/database中设置长度,看起来像149141530600.这是我在写这个答案时获取的当前纪元时间。它对应于从1970年1月1日到复制值时经过的毫秒数。然后,如果您有该节点的监听器,则可以使用以下命令获取日历:

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

如果您只想将服务器设置为的时间(将其保存在数据库中毫无意义),您可以使用特殊节点:

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

此节点的侦听器返回Double,表示设备时间和服务器时间之间的近似偏移量。然后,您可以使用

设置Calendar

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

答案 1 :(得分:0)

您可以使用以下内容。

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.

如果以字符串形式返回ServerValue.TIMESTAMP,则可以使用Long.parseLong(Server.TIMESTAMP);

解析字符串