Java获取 当前日期 之后 或 之前 多少天 日期工具类


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

/**
 * 获取 当前日期 之后 或 之前 7天 日期工具类
 *
 * @author xiwh
 */
public class DateUtil {

    /**
     * 获取未来任意天内的日期数组
     *
     * @param intervals intervals天内
     * @return 日期数组
     */
    public static ArrayList futureDate(int intervals) {
        ArrayList futureDaysList = new ArrayList<>();
        for (int i = 0; i < intervals; i++) {
            futureDaysList.add(getFutureDate(i));
        }
        return futureDaysList;
    }

    /**
     * 获取未来第几天的日期
     *
     * @param past
     * @return
     */
    public static String getFutureDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }

    /**
     * 获取过去任意天内的日期数组
     *
     * @param intervals intervals天内
     * @return 日期数组
     */
    public static ArrayList pastDate(int intervals) {
        ArrayList pastDaysList = new ArrayList<>();
        for (int i = 0; i < intervals; i++) {
            pastDaysList.add(getPastDate(i));
        }
        return pastDaysList;
    }

    /**
     * 获取过去第几天的日期
     *
     * @param past
     * @return
     */
    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }

    public static void main(String[] args) {
        //过去
        System.out.println(pastDate(7));
        //未来
        System.out.println(futureDate(7));
    }

}

 

转载请注明出处:BestEternity亲笔。

你可能感兴趣的:(java,jvm,servlet)