📜  Java SQL Timestamp getNanos()函数及示例

📅  最后修改于: 2022-05-13 01:55:17.802000             🧑  作者: Mango

Java SQL Timestamp getNanos()函数及示例

getNanos()函数是Java SQL 的Timestamp 类的一部分。该函数用于获取Timestamp 对象的秒值的小数部分。该函数返回对象的 nanos 值。

函数签名:

public int getNanos()

句法:

ts1.getNanos();

参数:该函数不接受任何参数。

返回值:函数返回一个整数值,它是对象的 nanos 值

异常:函数没有抛出任何异常

下面的例子说明了 getNanos()函数的使用

示例 1:创建时间戳并使用 getNanos() 获取时间戳对象的小数部分。

// Java program to demonstrate the
// use of getNanos() 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 timestamp object's
            // seconds' fractional part
            System.out.println("New Timestamp time : "
                               + ts.toString());
            System.out.println(" Fractional Part :"
                               + ts.getNanos());
        }
  
        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
 Fractional Part :1000000

示例 2:创建时间戳并使用 getNanos() 获取时间戳对象的小数部分,并且不设置任何秒的小数值

// Java program to demonstrate the
// use of getNanos() 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());
  
            // Display the timestamp object's
            // seconds' fractional part
            System.out.println("Fractional Part : "
                               + ts.getNanos());
        }
  
        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
Fractional Part : 0

参考: https: Java/sql/Timestamp.html