一、什麼是Date和Timestamp
在Java中,Date和Timestamp都是表示時間的類,它們的區別在於精度不同。
Date的精度只能到毫秒,而Timestamp的精度可以到納秒級別,因此在需要更高精度的時間計算中,應使用Timestamp。
二、Date轉換為Timestamp的方式
Java中提供了兩種方式將Date轉換為Timestamp:直接轉換和通過字元串轉換。
1、直接轉換
Date date = new Date(); Timestamp timestamp1 = new Timestamp(date.getTime());
在這種方式中,我們可以通過Date的getTime()方法獲取其對應的時間戳,並將其傳遞給Timestamp的構造函數。
2、通過字元串轉換
String str = "2022-01-01 00:00:00"; Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str); Timestamp timestamp2 = new Timestamp(date.getTime());
在這種方式中,我們首先需要將字元串轉換為Date類型,然後再將其轉換為Timestamp。
這裡需要注意的是,需要使用SimpleDateFormat類來解析字元串,通過指定對應的格式,將字元串轉換為Date類型。
三、Timestamp轉換為Date的方式
與將Date轉換為Timestamp相反,我們同樣可以通過兩種方式將Timestamp轉換為Date:Timestamp的構造函數和格式化字元串。
1、Timestamp的構造函數
Timestamp timestamp = new Timestamp(System.currentTimeMillis()); Date date1 = new Date(timestamp.getTime());
在這種方式中,我們可以通過Timestamp的getTime()方法獲取其對應的時間戳,並將其傳遞給Date的構造函數。
2、格式化字元串
String str = "2022-01-01 00:00:00"; Timestamp timestamp = Timestamp.valueOf(str); Date date2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str);
在這種方式中,我們可以通過Timestamp類的valueOf()方法將字元串轉換為Timestamp類型,然後通過SimpleDateFormat類將其轉換為Date類型。
四、完整代碼示例
import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Date; public class Test { public static void main(String[] args) throws Exception { // Date轉換為Timestamp Date date = new Date(); Timestamp timestamp1 = new Timestamp(date.getTime()); String str = "2022-01-01 00:00:00"; date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str); Timestamp timestamp2 = new Timestamp(date.getTime()); // Timestamp轉換為Date Timestamp timestamp = new Timestamp(System.currentTimeMillis()); Date date1 = new Date(timestamp.getTime()); str = "2022-01-01 00:00:00"; timestamp = Timestamp.valueOf(str); Date date2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str); } }
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/279841.html