当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java LocalDateTime withSecond()用法及代码示例


Java中LocalDateTime类的withSecond()方法用于获取此LocalDateTime的副本,并将秒数更改为作为此方法的参数传递的秒数。此LocalDateTime的其余值保持不变。

用法:

public LocalDateTime withSecond(int seconds)

参数:此方法接受单个强制性参数seconds,该参数指定要在结果LocalDateTime实例中设置的秒。该秒的值的范围可以从0到59。


返回值:该函数返回一个LocalDateTime实例,该实例的秒数更改为作为此方法的参数传递的秒数。此LocalDateTime的其余值保持不变。

异常:如果秒值无效,则该函数将引发DateTimeException。

以下示例程序旨在说明LocalDateTime.withSecond()方法:

示例1:

// Program to illustrate the withSecond() method 
  
import java.util.*; 
import java.time.*; 
  
public class GfG { 
    public static void main(String[] args) 
    { 
        // Get the LocalDateTime instance 
        LocalDateTime dt = LocalDateTime.now(); 
  
        // Get the String representation of this LocalDateTime 
        System.out.println("Original LocalDateTime: "
                           + dt.toString()); 
  
        // Get a new LocalDateTime with seconds 0 
        System.out.println("New LocalDateTime: "
                           + dt.withSecond(0)); 
    } 
}
输出:
Original LocalDateTime: 2018-11-30T10:39:52.924
New LocalDateTime: 2018-11-30T10:39:00.924

示例2:

// Program to illustrate the withSecond() method 
  
import java.util.*; 
import java.time.*; 
  
public class GfG { 
    public static void main(String[] args) 
    { 
        // Get the LocalDateTime instance 
        LocalDateTime dt 
            = LocalDateTime 
                  .parse("2015-04-06T10:15:30"); 
  
        // Get the String representation of this LocalDateTime 
        System.out.println("Original LocalDateTime: "
                           + dt.toString()); 
  
        // Get a new LocalDateTime with seconds 59 
        System.out.println("New LocalDateTime: "
                           + dt.withSecond(59)); 
    } 
}
输出:
Original LocalDateTime: 2015-04-06T10:15:30
New LocalDateTime: 2015-04-06T10:15:59

参考: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#withSecond(int)



相关用法


注:本文由纯净天空筛选整理自gopaldave大神的英文原创作品 LocalDateTime withSecond() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。