我尝试从 Firebase 时间戳获取日期和时间,如下所示:
Date date=new Date(timestamp*1000);
SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sfd.format(date);
但我得到的结果如下:
:02-02-48450 04:21:54
:06-02-48450 10:09:45
:07-02-48450 00:48:35
如您所见,今年与我们生活的年份不同。
所以,请帮我解决这个问题。
您的时间戳
1466769937914
等于2016-06-24 12:05:37 UTC
。问题是您将 timestamp
乘以 1000。但是您的 timestamp
已经保存了以毫秒为单位而不是以秒为单位的值(这个错误的假设很可能是您进行乘法的原因)。结果你得到 1466769937914000
转换后等于 48450-02-01 21:51:54 UTC
。因此从技术上讲,一切正常,您得到的结果是正确的。您需要修复的只是输入数据,解决方案非常简单 - 只需删除乘法即可:
SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sfd.format(new Date(timestamp));
如果您只需要从 Timestamp 获取
Date
对象,Timestamp 实例附带一个 toDate()
方法,该方法返回 Date
实例。
为了清楚起见:
Date javaDate = firebaseTimestampObject.toDate()
根据 Firebase 文档,可用的 JSON 类型有:
String
Long
Double
Boolean
Map<String, Object>
List<Object>
引用另一篇Stack Overflow帖子,我建议你使用JSON日期字符串格式
yyyy-MM-dd'T'HH:mm:ss.SSSZ
而不是纪元时间戳。
比较
1335205543511
与2012-04-23T18:25:43.511Z
,你可以注意到:
.toDate()
方法应该就是你所需要的您可能喜欢这些文档这里
作为额外的好处,您可能需要非常高度人类可读的输出
.toDate().toDateString()
.toDate().toLocaleDateString()
.toDate().toTimeString()
.toDate().toLocaleTimeString()
但是,如果您收到一个对象,您可能会这样做
{JSON.stringify(createdAt.toDate()).replace(/['"]+/g, '')}
将对象转换为字符串,然后替换字符串周围的引号。
总毫秒=(时间.秒+(时间.纳秒)*0.00000001)*1000。 // 1 纳秒=1e-9 表示 0.00000001
新日期(总毫秒)
String time=dataSnapshot.child("timeStamp").getValue().toString(); Long t=Long.parseLong(时间);
日期 myDate = 新日期(t*1000);
结果
5 月 11 日星期五 05:37:58 GMT+06:30
对于日期,您可以使用此代码:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
String date = DateFormat.format("dd-MM-yyyy", calendar).toString();
时间:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
String date = DateFormat.format("hh:mm", calendar).toString();
我认为有点晚了,但最简单的方法就是:
(new Date(timestamp.toDate())).toDateString()
在放置时间戳的 Date() 中添加
.toDate()
到时间戳变量,如@jasonleonhard所说。也许只是一个例子
new Date(timestamp.toDate())
在 Kotlin 中你可以这样做:-
val time = popup.get("date") as Timestamp
Log.e("time", " ${time.seconds*1000}")
输出:-
1713551400000