如何在android中使用日历显示日期和时间。喜欢2天前,1个月前。我试过没有使用日历。但是如果我们使用日历,我们可以避免每月28天和30天的问题。怎么做?
答案 0 :(得分:2)
遵循以下3个简单步骤: 1.保存活动发生的时间/日期(您想要显示$ months或$ days) 2.计算当前时间/日期。 3.在当前时间和上次保存时间之间取一个差异,然后使用相同的方法显示您想要的结果。
String dateStart = "01/14/2017 10:20:18";
String dateStop = "01/15/2018 11:41:38";
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
} catch (Exception e) {
e.printStackTrace();
}
答案 1 :(得分:0)
请检查下面的代码可能是您觉得有用
public static String getAgoTime(String p_date, SimpleDateFormat p_dateFormat) throws Throwable {
String message_Time = "";
// SimpleDateFormat m_dateFormater = new SimpleDateFormat(p_dateFormat);
Date m_currentdate = Calendar.getInstance().getTime();
String m_today = p_dateFormat.format(m_currentdate);
Date showTime = p_dateFormat.parse(p_date);
Date server_date = new SimpleDateFormat(Constants.SHOW_DATE_FORMAT).parse(p_date);
Date today_date = new SimpleDateFormat(Constants.SHOW_DATE_FORMAT).parse(m_today);
long m_diff = today_date.getTime() - server_date.getTime();
int hours = (int) (m_diff / (1000 * 60 * 60));
int mins = (int) ((m_diff / (1000 * 60)) % 60);
if (server_date.compareTo(today_date) == 0) {
/*
if (hours == 0) {
message_Time = String.valueOf(mins + " mins ago");
} else if (hours > 1 && hours < 23) {
message_Time = new SimpleDateFormat("hh:mm a").format(m_date1);
}
*/
message_Time = new SimpleDateFormat(Constants.SHOW_TIME_FORMAT).format(showTime);
} else if (server_date.compareTo(today_date) < 0) {
message_Time = new SimpleDateFormat(Constants.SHOW_INDEX_DATE).format(server_date);
}
return message_Time;
}
答案 2 :(得分:0)
希望这会有所帮助。
private long getTimesAgo(String dateValue){
try{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone(Constants.DateFormat.GMT));
long time = sdf.parse(dateValue).getTime();
long now = System.currentTimeMillis();
CharSequence ago = DateUtils.getRelativeTimeSpanString(time, now, DateUtils.MINUTE_IN_MILLIS);
return ago.toString();
}catch (Exception e){
return 0;
}
}