溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何解決java.sql.Timestamp丟失精度的問題

發(fā)布時(shí)間:2021-09-10 15:47:38 來源:億速云 閱讀:369 作者:柒染 欄目:開發(fā)技術(shù)

如何解決java.sql.Timestamp丟失精度的問題,很多新手對此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

java.sql.Timestamp丟失精度

Timestamp的構(gòu)造函數(shù)Timestamp(long time) 會(huì)丟失納秒部分的精度

需要重新補(bǔ)償

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 可以精確到小數(shù)秒 一般存儲(chǔ)的格式:2016-12-18 11:05:36.531

Timestamp 可以獲取當(dāng)前時(shí)間,也可以把字符串裝換成Timestamp類型

1. 獲取當(dāng)前時(shí)間

如何解決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類型轉(zhuǎn)換為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轉(zhuǎn)換為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);
}

整個(gè)演示類的代碼:

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

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI