欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

解决java.sql.Timestamp丢失精度的问题

程序员文章站 2022-03-07 07:53:24
目录java.sql.timestamp丢失精度java.sql.timestamp类的使用2.string类型转换为timestamp3.timestamp转换为string类型java.sql.t...

java.sql.timestamp丢失精度

timestamp的构造函数timestamp(long time) 会丢失纳秒部分的精度

需要重新补偿

        timestamp t1 = timestamp.valueof("2019-12-13 15:19:53.2202080");        
        timestamp t2 = new timestamp(1576250393220208000l / 1000000l);
        t2.setnanos((int) (1576250393220208000l % 1000000000l));

java.sql.timestamp类的使用

timestamp 可以精确到小数秒 一般存储的格式:2016-12-18 11:05:36.531

timestamp 可以获取当前时间,也可以把字符串装换成timestamp类型

1. 获取当前时间

解决java.sql.Timestamp丢失精度的问题

@test
public void getcurrenttime(){
	//第一种
	date date = new date();
	timestamp currenttime1 = new timestamp(date.gettime());
	system.out.println("currenttime1:"+currenttime1);
	//第二种
	timestamp currenttime2 = new timestamp(system.currenttimemillis());
	system.out.println("currenttime2:"+currenttime2);
}

2.string类型转换为timestamp

解决java.sql.Timestamp丢失精度的问题

@test
public void stringconverttimestamp(){
	string timestr = "2016-12-18 11:16:33.706";
	timestamp ts = timestamp.valueof(timestr);
	system.out.println(ts);
}

3.timestamp转换为string类型

解决java.sql.Timestamp丢失精度的问题

@test
public void timestampconvertstring(){
	simpledateformat sdf = new simpledateformat("yyy-mm-dd hh:mm:ss");
	timestamp currenttime = new timestamp(system.currenttimemillis());
	string timestr = sdf.format(currenttime);
	system.out.println(timestr);
}

整个演示类的代码:

package com.demo; 
import java.sql.timestamp;
import java.text.simpledateformat;
import java.util.date; 
import org.junit.test; 
public class demotimestamp {
	@test
	public void getcurrenttime(){
		//第一种
		date date = new date();
		timestamp currenttime1 = new timestamp(date.gettime());
		system.out.println("currenttime1:"+currenttime1);
		//第二种
		timestamp currenttime2 = new timestamp(system.currenttimemillis());
		system.out.println("currenttime2:"+currenttime2);
	}
	@test
	public void stringconverttimestamp(){
		string timestr = "2016-12-18 11:16:33.706";
		timestamp ts = timestamp.valueof(timestr);
		system.out.println(ts);
	}
	@test
	public void timestampconvertstring(){
		simpledateformat sdf = new simpledateformat("yyy-mm-dd hh:mm:ss");
		timestamp currenttime = new timestamp(system.currenttimemillis());
		string timestr = sdf.format(currenttime);
		system.out.println(timestr);
	}
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。