当用户从日历对话框中选择日期时间时,我想显示一组用户可理解的日期时间格式。
例如:
- 我不选择格式化并显示默认当前时间戳的日期。我希望 TextView 显示“现在”,而不是“2014 年 5 月 9 日上午 07:40”的日期时间。
- 如果我从日历对话框中选择时间“08:00 AM”(相对于当前时间 07:00 AM),则应显示为“再过 1 小时”。
- 超过一天的任何内容都会显示“日期 - 时间”(现有格式)。
最佳答案
我最近使用 Joda-Time 实现了同样的事情.
通过使用它,您可以获得不同格式的时差。示例代码
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.MONTH, Calendar.MAY);
cal.set(Calendar.DATE, 09);
cal.set(Calendar.HOUR_OF_DAY, 9);
Date startDate = cal.getTime();
//Use JodaTime to calculate difference
Period period = getTimePassedSince(startDate);
//Extract values and display
long days= Math.abs(period.getDays()));
long hours= Math.abs(period.getHours()));
long minitues =Math.abs(period.getMinutes()));
long secnds =Math.abs(period.getSeconds()));
...
public static Period getTimePassedSince(Date initialTimestamp){
DateTime initDT = new DateTime(initialTimestamp.getTime());
DateTime now = new DateTime();
Period p = new Period(initDT, now, PeriodType.dayTime()).normalizedStandard( PeriodType.dayTime());
return p;
}
关于java - 将当前日期时间 [时间戳] 与从日历对话框中选择的日期时间进行比较,并以用户可理解的方式显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23555611/