如何将 Firebase 时间戳转换为日期和时间

问题描述 投票:0回答:10

我尝试从 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

如您所见,今年与我们生活的年份不同。

所以,请帮我解决这个问题。

android datetime timestamp
10个回答
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));

17
投票

如果您想从 Timestamp 获取 Date 实例

如果您只需要从 Timestamp 获取

Date
对象,Timestamp 实例附带一个
toDate()
方法,该方法返回
Date
实例。

为了清楚起见:

Date javaDate = firebaseTimestampObject.toDate()

6
投票

根据 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
,你可以注意到:

  • 它是人类可读的,但也简洁
  • 排序正确
  • 它包括秒的小数部分,这可以帮助重新建立年表
  • 符合ISO 8601

ISO 8601 已在国际上得到认可十多年,并得到 W3CRFC3339XKCD

的认可

6
投票

.toDate()
方法应该就是你所需要的

您可能喜欢这些文档这里

作为额外的好处,您可能需要非常高度人类可读的输出

仅日期选项

.toDate().toDateString()

.toDate().toLocaleDateString()

仅限时间选项

.toDate().toTimeString()

.toDate().toLocaleTimeString()

物体

但是,如果您收到一个对象,您可能会这样做

{JSON.stringify(createdAt.toDate()).replace(/['"]+/g, '')}

将对象转换为字符串,然后替换字符串周围的引号。


3
投票
  • firebase 时间基本上是秒和纳秒的组合 时间={ 秒:1612974698, 纳秒:786000000 }

总毫秒=(时间.秒+(时间.纳秒)*0.00000001)*1000。 // 1 纳秒=1e-9 表示 0.00000001

新日期(总毫秒)


1
投票

String time=dataSnapshot.child("timeStamp").getValue().toString(); Long t=Long.parseLong(时间);

日期 myDate = 新日期(t*1000);

结果


5 月 11 日星期五 05:37:58 GMT+06:30


0
投票

对于日期,您可以使用此代码:

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

0
投票

我认为有点晚了,但最简单的方法就是:

(new Date(timestamp.toDate())).toDateString()


0
投票

在放置时间戳的 Date() 中添加

.toDate()

到时间戳变量,如@jasonleonhard所说。也许只是一个例子

new Date(timestamp.toDate())

0
投票

在 Kotlin 中你可以这样做:-

val time = popup.get("date") as Timestamp
 Log.e("time", " ${time.seconds*1000}")

输出:-

1713551400000

© www.soinside.com 2019 - 2024. All rights reserved.