Selaa lähdekoodia

作者:张哲
时间:2023/03/29
类型:开发
描述:里程碑(3) 日期计算

zizg 1 vuosi sitten
vanhempi
commit
86b47e8138
1 muutettua tiedostoa jossa 16 lisäystä ja 19 poistoa
  1. 16 19
      src/main/java/com/redxun/knowledge/utils/DateUtils.java

+ 16 - 19
src/main/java/com/redxun/knowledge/utils/DateUtils.java

@@ -3,9 +3,11 @@ package com.redxun.knowledge.utils;
 import org.apache.commons.lang.time.DateFormatUtils;
 
 import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
 import java.time.format.DateTimeFormatter;
-import java.time.temporal.TemporalAdjusters;
-import java.util.Calendar;
+import java.time.temporal.ChronoUnit;
+
 import java.util.Date;
 
 /**
@@ -37,17 +39,17 @@ public class DateUtils {
     }
 
     /**
-     * 获取某年第一天日期
+     * 获取某年第一天日期(一年前的日期)
      * @param year 年份
      * @return Date
      */
     public static Date getFirstOfYear(int year){
-        Calendar calendar = Calendar.getInstance();
-        calendar.clear();
-        calendar.set(Calendar.YEAR, year);
-        return calendar.getTime();
-    }
+        LocalDateTime nowYear = LocalDateTime.now();
+        nowYear = nowYear.minus(1, ChronoUnit.YEARS);
+        Date date = Date.from(nowYear.atZone(ZoneId.systemDefault()).toInstant());
+        return date;
 
+    }
 
 
     /**
@@ -56,11 +58,7 @@ public class DateUtils {
      * @return Date
      */
     public static Date getLastOfYear(int year){
-        Calendar calendar = Calendar.getInstance();
-        calendar.clear();
-        calendar.set(Calendar.YEAR, year);
-        calendar.roll(Calendar.DAY_OF_YEAR, -1);
-        return calendar.getTime();
+        return new Date();
     }
 
     /**
@@ -71,10 +69,10 @@ public class DateUtils {
      * @return
      */
     public static String getFirstOfMonth(int year,int month,int day){
-        LocalDate date = LocalDate.of(year, month, day);
-        LocalDate firstDay = date.with(TemporalAdjusters.firstDayOfMonth());
+        LocalDate date = LocalDate.now();
+        date = date.minus(29, ChronoUnit.DAYS);
         DateTimeFormatter df = DateTimeFormatter.ofPattern(datePattern);
-        String dateStr = firstDay.format(df);
+        String dateStr = date.format(df);
         return dateStr;
     }
 
@@ -86,10 +84,9 @@ public class DateUtils {
      * @return
      */
     public static String getLastOfMonth(int year,int month,int day){
-        LocalDate date = LocalDate.of(year, month, day);
-        LocalDate lastDay = date.with(TemporalAdjusters.lastDayOfMonth());
+        LocalDate date = LocalDate.now();
         DateTimeFormatter df = DateTimeFormatter.ofPattern(datePattern);
-        String dateStr = lastDay.format(df);
+        String dateStr = date.format(df);
         return dateStr;
     }
 }