Java日期方法工具类

不 定 时 更 新 ~

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

/**
 * @Author: zhangximing
 * @Email: [email protected]
 * @Date: 2023/10/10 11:41
 * @Description: 日期工具类
 */
public class DateUtils {

    /**
     * 获取提前多少小时的日期时间
     * @param hour
     * @return
     */
    public static String getBeforeByHourTime(int hour){

        String returnstr = "";

        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - hour);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        returnstr = df.format(calendar.getTime());

        return returnstr;

    }

    /**
     * 提前多少天
     * @param days
     * @return
     */
    public static String getBeforeDays(int days) {

        String returnstr = "";

        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - days);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        returnstr = df.format(calendar.getTime());

        return returnstr;
    }

    /**
     * 获取本月第一天
     * @return
     */
    public static String getCurrentMonthFirstDay(){
        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        // 将日期设置为第一天
        calendar.set(Calendar.DAY_OF_MONTH, 1);

        // 获取本月第一天的日期
        Date currentMonthFirstDay = calendar.getTime();

        return sdf.format(currentMonthFirstDay);
    }

    /**
     * 获取指定日期的上个月第一天日期
     * @param currentMonthFirstDay
     * @return
     */
    public static String getLastMonthFirstDay(String currentMonthFirstDay){
        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date date = null;
        try {
            date = sdf.parse(currentMonthFirstDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        calendar.setTime(date);

        // 将日期设置为上个月
        calendar.add(Calendar.MONTH, -1);

        // 将日期设置为第一天
        calendar.set(Calendar.DAY_OF_MONTH, 1);

        // 获取上个月第一天的日期
        Date lastMonthFirstDay = calendar.getTime();

        return sdf.format(lastMonthFirstDay);
    }

}

你可能感兴趣的:(分享,java,日期方法)