IT编程 > 开发语言 > Java

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

26人参与2021-09-15

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. 获取当前时间

@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

@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类型

@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);
	}
}

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

您对本文有任何疑问!!点此进行留言回复

推荐阅读

猜你喜欢

结对编程-中小学试卷生成程序-李晓彤+凌嘉文

09-19

Java 8 lambda初试示例详解

07-22

成年男性如何挑选衣服?

12-12

java 出现问题javax.servlet.http.HttpServlet was not found解决方法

07-22

java正则表达式简单应用

07-22

SpringBoot图文教程14—SpringBoot集成EasyExcel「上」

03-11

判断点与圆的位置关系

07-03

Java实现的质因数分解操作示例【基于递归算法】

07-19

热门评论