public class CalendarCal {
/**
* 與當前時間比較,獲得多少年,多少月,多少天前,多少小時前,多小分鐘前
*
* @param calendar
* 與當前時間比較的日期值
* @return 格式化以後的字符串
*/
public String getDateCompareNow(Calendar calendar) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR) - calendar.get(Calendar.YEAR);
String strdate = null;
if (year > 0) {
strdate = year + "年前";
} else if (year == 0) {
int month = cal.get(Calendar.MONTH) - calendar.get(Calendar.MONTH);
if (month > 0) {
strdate = month + "月前";
} else if (month == 0) {
int day = cal.get(Calendar.DAY_OF_MONTH) - calendar.get(Calendar.DAY_OF_MONTH);
if (day > 0) {
strdate = day + "天前";
} else if (day == 0) {
int hour = cal.get(Calendar.HOUR_OF_DAY) - calendar.get(Calendar.HOUR_OF_DAY);
if (hour > 0) {
strdate = hour + "小時前";
} else if (hour == 0) {
int minute = cal.get(Calendar.HOUR_OF_DAY) - calendar.get(Calendar.HOUR_OF_DAY);
if (minute > 0) {
strdate = minute + "分鐘前";
} else if (minute == 0) {
strdate = "剛剛";
}
}
// SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); //
// 格式化對象
// strdate = sdf.format(calendar.getTime()); // 輸出格式化的日期
// strdate = DateUtil.dateToString(date,"HH:mm");
}
}
} else {
return "-1"; // 返回了一個負數
}
return strdate;
}
/**
* 測試代碼
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse("2013-10-02 15:53:10");
Calendar calendar = Calendar.getInstance(); // 日曆對象
calendar.setTime(date); // 設置當前日期
CalendarCal t = new CalendarCal();
String strdate = t.getDateCompareNow(calendar);
System.out.println(strdate);
}
}測試