Android中如何基于PHP返回的Datetime字符串计算已流逝时间
解决PHP返回的Datetime字符串转换与流逝时间计算问题
我来帮你搞定这个问题!你遇到的转换失败大概率是因为没匹配正确的日期格式,或者还在使用Java旧的Date/Calendar类(这些类确实坑很多)。推荐用Java 8及以上版本自带的java.time日期时间API,这是目前最规范、最不容易出错的方案。
步骤1:解析PHP返回的时间字符串到Java日期对象
PHP返回的格式是"yyyy-MM-dd HH:mm:ss",我们用LocalDateTime配合DateTimeFormatter来解析,代码如下:
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; // 定义匹配的日期格式(HH是24小时制,对应PHP返回的时间格式) DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 解析字符串为LocalDateTime对象 String createdAtStr = "2018-04-02 20:06:42"; LocalDateTime createdAt = LocalDateTime.parse(createdAtStr, formatter);
如果你的PHP服务返回的是UTC时间,而客户端需要用本地时区处理,可以加上时区转换:
import java.time.ZoneId; import java.time.ZonedDateTime; // 假设PHP返回的是UTC时间,转换为客户端本地时区 ZonedDateTime utcCreatedAt = createdAt.atZone(ZoneId.of("UTC")); ZonedDateTime localCreatedAt = utcCreatedAt.withZoneSameInstant(ZoneId.systemDefault());
步骤2:计算与当前时间的流逝间隔
获取当前时间后,用ChronoUnit或者Duration来计算不同单位的时间差:
import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; // 获取当前本地时间 LocalDateTime now = LocalDateTime.now(); // 计算各时间单位的差值 long seconds = ChronoUnit.SECONDS.between(createdAt, now); long minutes = ChronoUnit.MINUTES.between(createdAt, now); long hours = ChronoUnit.HOURS.between(createdAt, now); long days = ChronoUnit.DAYS.between(createdAt, now);
如果需要更灵活的时长拆分(比如同时显示天、小时、分钟),可以用Duration:
import java.time.Duration; Duration duration = Duration.between(createdAt, now); long days = duration.toDays(); long hours = duration.toHours() % 24; long minutes = duration.toMinutes() % 60; long seconds = duration.getSeconds() % 60;
步骤3:格式化显示流逝时间
把计算出的差值转换成用户友好的文本,比如"3天前"、"2小时15分钟前":
public String formatElapsedTime(LocalDateTime createdAt) { LocalDateTime now = LocalDateTime.now(); long days = ChronoUnit.DAYS.between(createdAt, now); if (days > 0) { return days + "天前"; } long hours = ChronoUnit.HOURS.between(createdAt, now); if (hours > 0) { return hours + "小时前"; } long minutes = ChronoUnit.MINUTES.between(createdAt, now); if (minutes > 0) { return minutes + "分钟前"; } return "刚刚"; }
为什么之前转换失败?
如果之前用SimpleDateFormat尝试转换,可能是格式字符串写错了(比如用了hh而不是HH,hh是12小时制,而PHP返回的是24小时制时间),或者没有捕获解析异常。另外旧的Date类本身设计有缺陷,线程不安全,非常不推荐使用。
内容的提问来源于stack exchange,提问作者user2682025
相关产品推荐
相关产品推荐

