共計 559 個字符,預(yù)計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以使用 java.util.Date
類和 java.sql.Timestamp
類來將日期轉(zhuǎn)換為時間戳。
以下是將日期轉(zhuǎn)換為時間戳的示例代碼:
import java.util.Date;
import java.sql.Timestamp;
public class DateToTimestampExample {public static void main(String[] args) {// 獲取當(dāng)前日期
Date date = new Date();
// 將日期轉(zhuǎn)換為時間戳
long timestamp = date.getTime();
// 創(chuàng)建 Timestamp 對象
Timestamp ts = new Timestamp(timestamp);
// 輸出時間戳
System.out.println(" 時間戳: " + timestamp);
System.out.println("Timestamp 對象: " + ts);
}
}
輸出結(jié)果類似于:
時間戳: 1630958306809
Timestamp 對象: 2021-09-07 20:51:46.809
在上面的代碼中,date.getTime()
方法會返回自 1970 年 1 月 1 日以來的毫秒數(shù),然后使用 new Timestamp(timestamp)
構(gòu)造函數(shù)創(chuàng)建一個 Timestamp
對象。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完