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、結果: