Java中的 OffsetDateTime withSecond() 方法及示例
Java中 OffsetDateTime 类的withSecond()方法返回此 OffsetDateTime 的副本,其中秒数按参数中指定的方式更改。
句法:
public OffsetDateTime withSecond(int second)
参数:此方法接受单个参数秒,该参数指定要在结果中设置的秒数,范围从 0 到 59。
返回值:它返回一个基于此日期的 OffsetDateTime,其中包含请求的秒数且不为空。
异常:当秒值无效时,程序会抛出DateTimeException 。
下面的程序说明了withSecond()方法:
方案一:
// Java program to demonstrate the withSecond() method
import java.time.OffsetDateTime;
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 second-of-minute
System.out.println("Date1 after altering second-of-minute: "
+ date1.withSecond(40));
}
}
输出:
Date1: 2018-12-12T13:30:30+05:00
Date1 after altering second-of-minute : 2018-12-12T13:30:40+05:00
方案二:
// Java program to demonstrate the withSecond() 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 second-of-minute
System.out.println("Date1 after altering second-of-minute: "
+ date1.withSecond(70));
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
输出:
Date1: 2018-12-12T13:30:30+05:00
Exception: java.time.DateTimeException:
Invalid value for SecondOfMinute (valid values 0 - 59): 70
参考:https: Java/time/OffsetDateTime.html#withSecond(int)