获取某个时间前或者后的时间戳

1、程序代码:

package com.my.date;

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

public class DateUtil {

    public static void main(String[] args) {

        String dateStr = "2021-11-25 10:15:00";

        // 一秒前
        System.out.println("一秒前: " + getDateAfterTime(dateStr, -1, Calendar.SECOND));
        // 一秒后
        System.out.println("一秒后: " + getDateAfterTime(dateStr, 1, Calendar.SECOND));

        // 一分钟前
        System.out.println("一分钟前: " + getDateAfterTime(dateStr, -1, Calendar.MINUTE));
        // 一分钟后
        System.out.println("一分钟后: " + getDateAfterTime(dateStr, 1, Calendar.MINUTE));

        // 一小时前
        System.out.println("一小时前: " + getDateAfterTime(dateStr, -1, Calendar.HOUR));
        // 一小时后
        System.out.println("一小时后: " + getDateAfterTime(dateStr, 1, Calendar.HOUR));

        // 一天前
        System.out.println("一天前: " + getDateAfterTime(dateStr, -1, Calendar.DAY_OF_MONTH));
        // 一天后
        System.out.println("一天后: " + getDateAfterTime(dateStr, 1, Calendar.DAY_OF_MONTH));

        // 一周前
        System.out.println("一周前: " + getDateAfterTime(dateStr, -1, Calendar.WEEK_OF_MONTH));
        // 一周后
        System.out.println("一周后: " + getDateAfterTime(dateStr, 1, Calendar.WEEK_OF_MONTH));

        // 一月前
        System.out.println("一月前: " + getDateAfterTime(dateStr, -1, Calendar.MONTH));
        // 一月后
        System.out.println("一月后: " + getDateAfterTime(dateStr, 1, Calendar.MONTH));

        // 一年前
        System.out.println("一年前: " + getDateAfterTime(dateStr, -1, Calendar.YEAR));
        // 一年后
        System.out.println("一年后: " + getDateAfterTime(dateStr, 1, Calendar.YEAR));
    }


    /**
     * 获取某个时间,n 年/月/周/日/时/分/秒前或者后的时间
     * n为正时代表时间戳后的某个时间,n为负时代表时间戳前的某个时间,
     *
     * @param dateStr
     * @param time
     * @param timeType
     * @return
     */
    public static Date getDateAfterTime(String dateStr, int time, int timeType) {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar cal = Calendar.getInstance();
            cal.setTime(df.parse(dateStr));
            cal.add(timeType, time);
            return cal.getTime();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取某个时间,n 年/月/周/日/时/分/秒前或者后的时间
     * n为正时代表时间戳后的某个时间,n为负时代表时间戳前的某个时间,
     *
     * @param date
     * @param time
     * @param timeType
     * @return
     */
    public static Date getDateAfterTime(Date date, int time, int timeType) {
        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(timeType, time);
            return cal.getTime();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

2、结果:

  

posted @ 2021-12-20 10:43  北国浪子  阅读(1187)  评论(0编辑  收藏  举报