我有一个游戏客户端,一个Google App Engine服务器。 我的服务器向客户端发送一个 UTC 时间日期字符串,该字符串是自纪元以来的毫秒数,表示上次播放的日期戳。 我希望我的客户报告自上次播放以来的天数/小时/分钟数。 我在我的iOS客户端中工作,但无法让它在Android中工作。 我尝试了很多选项,有些使用 Joda-Time 一些 Date 对象是直的 Java,时间总是偏移几个小时。 奇怪的是时间不是整点。可能会关闭 2 小时 34 分钟。所以我认为我的问题不仅仅是时区问题,还是在整点不是?
从本质上讲,我需要获取此 UTC 时间,然后以 UTC 格式获取当前时间.. 比较差异以获得天/小时/分钟
这是我所拥有的,我正在使用Joda-Time库:
例如,我的服务器向我发送此字符串"1392392591.0"(恰好是太平洋标准时间上午 7:45 左右的 UTC 时间)
public String convertDateString ( String date ) {
Float gameEpoch = Float.parseFloat( date );
DateTime now = new DateTime();
DateTime gameTime = new DateTime(gameEpoch.longValue() * 1000 );
Period p = new Period(gameTime, now, PeriodType.dayTime());
String dateString = "";
if(p.getDays() > 0)
dateString = (p.getDays() + " days " + p.getHours() + " hours ago");
else if(p.getHours() > 0)
dateString = (p.getHours() + " hours " + p.getMinutes() + " minutes ago");
else if(p.getMinutes() > 0)
dateString = (p.getMinutes() + " minutes ago");
else
dateString = "Just Now";
return dateString;
}
不要从String
转换为Float
。浮点数只有 7 位有效数字,因此gameEpoch
总是不精确的。使用double
,或者更好的是,long
。
小马托尼的回答是正确的。
顺便说一下,在示例代码的后半部分,您工作得太辛苦了。Joda-Time 提供了一个 PeriodFormatterBuilder 类来帮助你生成这些描述性字符串。
此示例代码需要一些技巧,但会让你朝着正确的方向前进。
// Period(int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis)
Period period = new Period( 0, 0, 0, 2, 3, 4, 0, 0 );
PeriodFormatter formatter = new PeriodFormatterBuilder()
.printZeroAlways()
.appendYears()
.appendSuffix( " year", " years" )
.appendSeparator( ", " )
.printZeroRarelyLast()
.appendMonths()
.appendSuffix( " month", " months" )
.appendSeparator( ", " )
.appendWeeks()
.appendSuffix( " week", " weeks" )
.appendSeparator( ", " )
.appendDays()
.appendSuffix( " day", " days" )
.appendSeparator( ", " )
.appendHours()
.appendSuffix( " hour", " hours" )
.appendSeparator( ", and " )
.appendMinutes()
.appendSuffix( " minute", " minutes" )
.toFormatter();
String timeSpanDescription = formatter.print( period );
转储到控制台...
System.out.println( "period: " + period );
System.out.println( "timeSpanDescription: " + timeSpanDescription );
运行时...
period: P2DT3H4M
timeSpanDescription: 0 years, 2 days, 3 hours, and 4 minutes