java封装需要多久_Java封装的与当前时间比较,得到多少年,多少月,多少天前,多少小时前,多小分钟前...

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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值