获取某年月的最后一天

import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * @Description 时间转换工具类
 * @PackageName com.leo.tms.utils
 * @Author Simon Liu
 * @Date 2019年06月03日 10:44:28
 */
public class DateUtil {

    /*
     * @Description: 获取指定某年某月份的最后一天
     * @Date 2019/6/3 10:52
     * @param: yearMonth yyyy-MM格式
     * @return: java.lang.String
     */
    public static String getLastDayOfMonth(String yearMonth) {
        int year = Integer.parseInt(yearMonth.split("-")[0]);  //年
        int month = Integer.parseInt(yearMonth.split("-")[1]); //月
        Calendar cal = Calendar.getInstance();
        // 设置年份
        cal.set(Calendar.YEAR, year);
        // 设置月份
        cal.set(Calendar.MONTH, month - 1);
        // 获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DATE);
        // 设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        // 格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(cal.getTime());
    }

    /*
     * @Description: 如日期格式为 yyyyMM 则需要拼接个"-"
     */
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("201902");
        //sb.insert(6, "-00");
        sb.insert(4, "-");
        System.out.println(sb); //输出 2019-02
        System.out.println(getLastDayOfMonth(sb.toString())); //输出 20190228
    }

/**
 * @param  smdate
 * @param  bdate
 * @return int
 * @Description: 两个日期相差天数
 */
public static int daysBetween(Date smdate, Date bdate) throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    smdate = sdf.parse(sdf.format(smdate));
    bdate = sdf.parse(sdf.format(bdate));
    Calendar cal = Calendar.getInstance();
    cal.setTime(smdate);
    long time1 = cal.getTimeInMillis();
    cal.setTime(bdate);
    long time2 = cal.getTimeInMillis();
    long between_days = (time2 - time1) / (1000 * 3600 * 24);

    return Integer.parseInt(String.valueOf(between_days));
}

/**
 * @param  smdate
 * @param  bdate
 * @throws ParseException
 * @return int
 * @Description: 两个月份相差月数
 */
public static int monthsBetween(Date smdate, Date bdate) throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
    smdate = sdf.parse(sdf.format(smdate));
    bdate = sdf.parse(sdf.format(bdate));
    Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    cal1.setTime(smdate);
    cal2.setTime(bdate);
    int year = cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR);
    return year * 12 + cal2.get(Calendar.MONTH) - cal1.get(Calendar.MONTH);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值