當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。