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
// 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());
}
}
}
Java
// 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
New Timestamp time : 1970-01-01 00:00:10.001
示例 2:创建时间戳并使用 setNanos() 设置时间戳对象的小数部分,并将负 int 值作为参数传递。
Java
// 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 < 0
参考: https: Java/sql/Timestamp.html