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


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


LocalTime类的withSecond()方法用于获取此LocalTime的副本,并将秒数更改为作为此方法的参数传递的秒数。此LocalTime的其余值将保持不变。此实例是不可变的,不受此方法调用的影响。

用法:

public LocalTime withSecond(int second)

参数:此方法接受单个参数秒,该参数代表要在结果中设置的second-of-minute,范围为0到59。


返回值:此方法基于此时间(请求的秒数)返回LocalTime实例。

异常:如果第二个值无效,则此方法引发异常DateTimeException

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

示例1:

// Java program to demonstrate 
// LocalTime.withSecond() method 
  
import java.time.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a LocalTime object 
        LocalTime time 
            = LocalTime.parse("19:34:50.63"); 
  
        // print time 
        System.out.println("Old LocalTime: "
                           + time); 
  
        // Get a new LocalDateTime with seconds 4 
        LocalTime newtime = time.withSecond(4); 
  
        // print result 
        System.out.println("New LocalDateTime: "
                           + newtime); 
    } 
}
输出:
Old LocalTime: 19:34:50.630
New LocalDateTime: 19:34:04.630

示例2:

// Java program to demonstrate 
// LocalTime.withSecond() method 
  
import java.time.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a LocalTime object 
        LocalTime time 
            = LocalTime.parse("01:21:30.13"); 
  
        // print time 
        System.out.println("Old LocalTime: "
                           + time); 
  
        // Get a new LocalDateTime with seconds 23 
        LocalTime newtime = time.withSecond(23); 
  
        // print result 
        System.out.println("New LocalDateTime: "
                           + newtime); 
    } 
}
输出:
Old LocalTime: 01:21:30.130
New LocalDateTime: 01:21:23.130

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



相关用法


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