【发布时间】:2018-11-10 22:25:15
【问题描述】:
我找不到解决方案,我正在从 firebase 获取数据,其中一个字段是时间戳,看起来像这样 -> 1522129071。如何将其转换为日期?
Swift 示例(有效):
func readTimestamp(timestamp: Int) {
let now = Date()
let dateFormatter = DateFormatter()
let date = Date(timeIntervalSince1970: Double(timestamp))
let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .weekOfMonth])
let diff = Calendar.current.dateComponents(components, from: date, to: now)
var timeText = ""
dateFormatter.locale = .current
dateFormatter.dateFormat = "HH:mm a"
if diff.second! <= 0 || diff.second! > 0 && diff.minute! == 0 || diff.minute! > 0 && diff.hour! == 0 || diff.hour! > 0 && diff.day! == 0 {
timeText = dateFormatter.string(from: date)
}
if diff.day! > 0 && diff.weekOfMonth! == 0 {
timeText = (diff.day == 1) ? "\(diff.day!) DAY AGO" : "\(diff.day!) DAYS AGO"
}
if diff.weekOfMonth! > 0 {
timeText = (diff.weekOfMonth == 1) ? "\(diff.weekOfMonth!) WEEK AGO" : "\(diff.weekOfMonth!) WEEKS AGO"
}
return timeText
}
我对 Dart 的尝试:
String readTimestamp(int timestamp) {
var now = new DateTime.now();
var format = new DateFormat('HH:mm a');
var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp);
var diff = date.difference(now);
var time = '';
if (diff.inSeconds <= 0 || diff.inSeconds > 0 && diff.inMinutes == 0 || diff.inMinutes > 0 && diff.inHours == 0 || diff.inHours > 0 && diff.inDays == 0) {
time = format.format(date); // Doesn't get called when it should be
} else {
time = diff.inDays.toString() + 'DAYS AGO'; // Gets call and it's wrong date
}
return time;
}
它会返回 waaaaaaaay 关闭的日期/时间。
更新:
String readTimestamp(int timestamp) {
var now = new DateTime.now();
var format = new DateFormat('HH:mm a');
var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp * 1000);
var diff = date.difference(now);
var time = '';
if (diff.inSeconds <= 0 || diff.inSeconds > 0 && diff.inMinutes == 0 || diff.inMinutes > 0 && diff.inHours == 0 || diff.inHours > 0 && diff.inDays == 0) {
time = format.format(date);
} else {
if (diff.inDays == 1) {
time = diff.inDays.toString() + 'DAY AGO';
} else {
time = diff.inDays.toString() + 'DAYS AGO';
}
}
return time;
}
【问题讨论】:
-
我将假设您的时间戳格式错误。您的时间戳 int 数据是什么样的? (这将告诉我们它是以秒为单位的。毫秒或微秒。
-
我的手机上运行了适用于 ios 的应用程序,它显示了正确的格式化日期。使用来自同一个数据库的相同时间戳,它在 dart/flutter 中给出了奇怪的值。它看起来像这样 -> 1522129071。注意** 由于某种原因,所有时间戳都显示为相同。
-
-> 1522129071
-
当我从数据库中获取它时,它使用 swift 代码正确显示,但在 dart 中它显示 19:25 PM,它应该显示 15:50 PM,2 周前,4 周前,等等……
-
你能给我看一下firebase时间戳的截图吗?您是使用时间戳数据类型还是只输入毫秒?