Java时间处理方法

//获得下周一的日期
public Date getNextMonday(Date date){
Calendar cal = Calendar.getInstance();  
cal.setTime(getThisWeekTuesday(date));  
cal.add(Calendar.DATE, 6);  
return cal.getTime();
}
//获得上周二的日期
public Date getLastWeekTuesday(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(getThisWeekTuesday(date));
cal.add(Calendar.DATE, -7);
return cal.getTime();
    }

//获得当前周周二的日期
    public Date getThisWeekTuesday(Date date) {  
        Calendar cal = Calendar.getInstance();  
        cal.setTime(date);  
        // 获得当前日期是一个星期的第几天  
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);  
        if (1 == dayWeek) {  
            cal.add(Calendar.DAY_OF_MONTH, -1);  
        }  
        // 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一  
        cal.setFirstDayOfWeek(Calendar.MONDAY);  
        // 获得当前日期是一个星期的第几天  
        int day = cal.get(Calendar.DAY_OF_WEEK) - 1;  
        // 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值  
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);  
        return cal.getTime();
    }
    
//判断当前日期是周几
public int getDayOfWeek(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
if(calendar.get(Calendar.DAY_OF_WEEK) - 1 == 0){
return Calendar.DAY_OF_WEEK;
} else {
return calendar.get(Calendar.DAY_OF_WEEK) - 1;
}

    }

/* public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse("2018-02-03");
DateTime dateTime = new DateTime(date);
int dayOfWeek = dateTime.getDayOfWeek()-1;
int weekyear = dateTime.weekyear().get();
System.out.println("一周的第"+dayOfWeek+"天");
System.out.println(weekyear);
}*/
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse("2018-01-03");
Calendar cale = Calendar.getInstance();
cale.setTime(date);
        cale.add(Calendar.MONTH, 1);
        cale.set(Calendar.DAY_OF_MONTH, 0);
        String lastDay = sdf.format(cale.getTime());
        System.out.println("下月最后一天是 : " + lastDay);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值