java - 将当前日期时间 [时间戳] 与从日历对话框中选择的日期时间进行比较,并以用户可理解的方式显示

标签 java android date calendar

当用户从日历对话框中选择日期时间时,我想显示一组用户可理解的日期时间格式。

例如:

  1. 我不选择格式化并显示默认当前时间戳的日期。我希望 TextView 显示“现在”,而不是“2014 年 5 月 9 日上午 07:40”的日期时间。
  2. 如果我从日历对话框中选择时间“08:00 AM”(相对于当前时间 07:00 AM),则应显示为“再过 1 小时”。
  3. 超过一天的任何内容都会显示“日期 - 时间”(现有格式)。

最佳答案

我最近使用 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/

相关文章:

r - 特定日期的子集数据框

java - Android OrientationEventListener 进行多次调用

java - AtomiceInteger 没有按 forjointask 的预期增加

Android中心和调整 WebView 中的图像

android - 使用 getLayoutParams() 时出现空指针异常

java - 有没有办法知道应用程序安装了多长时间?

MySQL 循环日期到一周和一个月的开始

java - Tomcat 8.5 - 缓存警告泛滥

相当于System.Data.Services.Client的java包

objective-c - 使用 NSDateFormatter 解析日期字符串,月份从 0 开始