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


Java SQL Timestamp setNanos()用法及代码示例


setNanos()函数是Java SQL的Timestamp类的一部分。该函数用于设置Timestamp对象的秒值的小数部分。该函数将对象的Nanos值设置为给定值。

函数签名:

public void setNanos(int t)

用法:


ts1.setNanos(l);

参数:该函数接受int值t作为要设置的纳秒值的参数。

返回值:该函数不返回任何值。

异常:如果传递的参数小于0或大于999999999,该函数将引发IllegalArgumentException

以下示例说明了setNanos()函数的使用

范例1:创建一个时间戳,并使用setNanos()设置时间戳对象的小数部分。

// Java program to demonstrate the 
// use of setNanos() function 
  
import java.sql.*; 
  
public class solution { 
    public static void main(String args[]) 
    { 
  
        try { 
  
            // Create two timestamp objects 
            Timestamp ts = new Timestamp(10000); 
  
            // Display the timestamp object 
            System.out.println("Timestamp time:"
                               + ts.toString()); 
  
            // Set the value of the fractional part 
            // of timestamp object 
            // using setNanos function 
            ts.setNanos(1000000); 
  
            // Display the new timestamp object 
            System.out.println("New Timestamp time:"
                               + ts.toString()); 
        } 
  
        catch (IllegalArgumentException e) { 
  
            // Display the error if any error has occured 
            System.err.println(e.getMessage()); 
        } 
    } 
}
输出:
Timestamp time:1970-01-01 00:00:10.0
New Timestamp time:1970-01-01 00:00:10.001

范例2:创建一个时间戳,并使用setNanos()设置时间戳对象的小数部分,并传递整数int值作为参数。

// Java program to demonstrate the 
// use of setNanos() function 
  
import java.sql.*; 
  
public class solution { 
    public static void main(String args[]) 
    { 
  
        try { 
  
            // Create two timestamp objects 
            Timestamp ts = new Timestamp(10000); 
  
            // Display the timestamp object 
            System.out.println("Timestamp time:"
                               + ts.toString()); 
  
            // Set the value of the fractional part 
            // of timestamp object 
            // using setNanos function 
            ts.setNanos(-1000000); 
  
            // Display the new timestamp object 
            System.out.println("New Timestamp time:"
                               + ts.toString()); 
        } 
  
        catch (IllegalArgumentException e) { 
  
            // Display the error if any error has occured 
            System.out.println(e.getMessage()); 
        } 
    } 
}
输出:
Timestamp time:1970-01-01 00:00:10.0
nanos > 999999999 or 

参考: https:// docs.oracle.com/javase/7/docs/api/java/sql/Timestamp.html



相关用法


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