Java OffsetDateTime withDayOfYear()方法及示例
Java中OffsetDateTime类的 withDayOfYear() 方法返回该OffsetDateTime的副本,并按参数中指定的年份-月份进行修改。
语法
public OffsetDateTime withDayOfYear(int dayOfYear)
参数: 该方法接受一个参数 dayOfYear ,指定要在结果中设置的年月日,范围从1到365-366。
返回值: 它返回一个基于该日期的OffsetDateTime,该日期为所要求的年月日,且不为空。
异常 :当年月日值无效或年月日对该特定年份的月份无效时,程序会抛出一个 DateTimeException 。
以下程序说明了withDayOfYear()方法。
程序1 :
// Java program to demonstrate the withDayOfYear() method
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
public class GFG {
public static void main(String[] args)
{
// Parses the date1
OffsetDateTime date1
= OffsetDateTime
.parse(
"2018-12-12T13:30:30+05:00");
// Prints dates
System.out.println("Date1: " + date1);
// Changes the day of year
System.out.println("Date1 after altering day-of-year: "
+ date1.withDayOfYear(32));
}
}
输出。
Date1: 2018-12-12T13:30:30+05:00
Date1 after altering day-of-year: 2018-02-01T13:30:30+05:00
程序2
// Java program to demonstrate the withDayOfYear() method
import java.time.OffsetDateTime;
public class GFG {
public static void main(String[] args)
{
try {
// Parses the date1
OffsetDateTime date1
= OffsetDateTime
.parse(
"2018-12-12T13:30:30+05:00");
// Prints dates
System.out.println("Date1: " + date1);
// Changes the day of year
System.out.println("Date1 after altering day-of-year: "
+ date1.withDayOfYear(367));
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
输出。
Date1: 2018-12-12T13:30:30+05:00
Exception: java.time.DateTimeException:
Invalid value for DayOfYear
(valid values 1 - 365/366): 367
参考资料 : https://docs.oracle.com/javase/10/docs/api/java/time/OffsetDateTime.html#withDayOfYear(int)