Looly 5 years ago
parent
commit
e7bc77aff5

+ 10 - 0
hutool-core/src/main/java/cn/hutool/core/date/DateTime.java

@@ -455,6 +455,16 @@ public class DateTime extends Date {
 	}
 
 	/**
+	 * 获得指定日期是这个日期所在年份的第几天<br>
+	 *
+	 * @return 天
+	 * @since 5.3.6
+	 */
+	public int dayOfYear() {
+		return getField(DateField.DAY_OF_YEAR);
+	}
+
+	/**
 	 * 获得指定日期是星期几,1表示周日,2表示周一
 	 *
 	 * @return 星期几

+ 13 - 1
hutool-core/src/main/java/cn/hutool/core/date/DateUtil.java

@@ -20,6 +20,7 @@ import java.time.LocalDateTime;
 import java.time.LocalTime;
 import java.time.OffsetDateTime;
 import java.time.OffsetTime;
+import java.time.Year;
 import java.time.ZoneId;
 import java.time.ZonedDateTime;
 import java.time.format.DateTimeFormatter;
@@ -259,7 +260,7 @@ public class DateUtil extends CalendarUtil {
 	 * @since 5.3.6
 	 */
 	public static int dayOfYear(Date date) {
-		return DateTime.of(date).getField(DateField.DAY_OF_YEAR);
+		return DateTime.of(date).dayOfYear();
 	}
 
 	/**
@@ -1863,6 +1864,17 @@ public class DateUtil extends CalendarUtil {
 		return LocalDateTime.ofInstant(dateTime.toInstant(), dateTime.getZoneId());
 	}
 
+	/**
+	 * 获得指定年份的总天数
+	 *
+	 * @param year 年份
+	 * @return 天
+	 * @since 5.3.6
+	 */
+	public static int lengthOfYear(int year) {
+		return Year.of(year).length();
+	}
+
 	// ------------------------------------------------------------------------ Private method start
 
 	/**

+ 8 - 9
hutool-core/src/test/java/cn/hutool/core/date/DateUtilTest.java

@@ -4,7 +4,6 @@ import cn.hutool.core.collection.CollUtil;
 import cn.hutool.core.date.BetweenFormater.Level;
 import cn.hutool.core.date.format.FastDateFormat;
 import org.junit.Assert;
-import org.junit.Ignore;
 import org.junit.Test;
 
 import java.text.SimpleDateFormat;
@@ -381,14 +380,6 @@ public class DateUtilTest {
 	}
 
 	@Test
-	@Ignore
-	public void parseTest8() {
-		String str = "2020-04-24 9:00:00";
-		DateTime dateTime = DateUtil.parse(str);
-		Assert.assertEquals("2019-06-01 19:45:43", dateTime.toString());
-	}
-
-	@Test
 	public void parseAndOffsetTest() {
 		// 检查UTC时间偏移是否准确
 		String str = "2019-09-17T13:26:17.948Z";
@@ -762,4 +753,12 @@ public class DateUtilTest {
 		final long weekCount = DateUtil.betweenWeek(start, end, true);
 		Assert.assertEquals(30L, weekCount);
 	}
+
+	@Test
+	public void dayOfYearTest() {
+		int dayOfYear = DateUtil.dayOfYear(DateUtil.parse("2020-01-01"));
+		Assert.assertEquals(1, dayOfYear);
+		int lengthOfYear = DateUtil.lengthOfYear(2020);
+		Assert.assertEquals(366, lengthOfYear);
+	}
 }