您的位置:首页 > 编程语言 > Java开发

Java封装的与当前时间比较,得到多少年,多少月,多少天前,多少小时前,多小分钟前

2013-10-09 10:09 411 查看
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: