java日期类(三) 日期工具类(拿来即用,很多你工作中需要的时间处理都有)

目录

工具类


public class DateUtil {


//将  格式为  yyyy-MM-dd字符串类型的  时间  转为   Date类型

	public static Date parse(String strDate) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.parse(strDate);
	}





//  根据出生日期   获取  到年龄
	public static String getAge(String date) {

		try {
			Date birthDay = parse(date);
			Calendar cal = Calendar.getInstance();
			if (cal.before(birthDay)) {
				//出生日期晚于当前时间,无法计算
				throw new IllegalArgumentException(
					"The birthDay is before Now.It's unbelievable!");
			}
			//当前年份
			int yearNow = cal.get(Calendar.YEAR);
			//当前月份
			int monthNow = cal.get(Calendar.MONTH);
			//当前日期
			int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
			cal.setTime(birthDay);
			int yearBirth = cal.get(Calendar.YEAR);
			int monthBirth = cal.get(Calendar.MONTH);
			int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
			//计算整岁数
			int age = yearNow - yearBirth;
			if (monthNow <= monthBirth) {
				if (monthNow == monthBirth) {
					if (dayOfMonthNow < dayOfMonthBirth){
						//当前日期在生日之前,年龄减一
						age--;
					}
				} else {
					age--;//当前月份在生日之前,年龄减一
				}
			} return age+"";
		}catch (Exception e){

		}
		return "未知";
	}







/**
     * 判断时间是否在时间段内
     *
     * @param nowTime
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean belongCalendar(Date nowTime, Date beginTime,
                                         Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }







	/**
	 * isodate时间格式转换
	 * @param datetime  Thu Jul 29 22:31:27 CST 2010
	 * @return
	 */
	public static String getISODateStr(String datetime){
		SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", java.util.Locale.US);
		Date date = null;
		try {
			date = sdf.parse(datetime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String newDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
		return newDate;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一写代码就开心

你的打赏将是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值