将localDateTime转换为Java中的时间戳
时间:2020-02-23 14:35:04 来源:igfitidea点击:
在本教程中,我们将如何将localDateTime转换为时间戳。
在学习如何将LocalDateTime转换为Timestamp之前,让我们了解LocalDateTime和时间戳,并了解这一转换的重要性。
localDateTime
LocalDateTime在Java 8中没有内容。
LocalDateTime可以导入时间包: import java.time.LocalDateTime;
LocalDateTime是一个用于表示日期日期为期一秒钟的日期的不可变的对象。
时间以纳秒精度表示。
例子 :
LocalDateTime current_date_time = LocalDateTime.now(); //returns time and date object of today's date. System.out.println(current_date_time); //printing the time and date
输出 :
2017-11-07T10:16:02.234214500
注意:上面的输出是根据我编译我的代码的时间。
随着时间和日期变化,输出可能会发生变化。 LocalDateTime.now():在特定时间内返回localDateTime对象。
时间戳 Timestamp
Timestamp类可以从java.sql包导入类,即, import java.sql.Timestamp;此类允许JDBC API识别为SQL时间戳。
SQL时间戳具有分数秒值,此类对象使时间戳兼容SQL时间戳,使JDBC API容易按时运行查询并操作数据库。
Timestamp提供格式化和解析操作以支持JDBC的方法。
将localDateTime转换为时间戳
你可以使用时间戳的 valueOf()将localDateTime转换为时间戳的方法。
将localDateTeme转换为Timestamp有助于我们将时间转换为与SQL Timestamp数据类型兼容的时间戳。
Timestamp.valueof(LocalDateTime local):回报 Timestamp具有相同日期的对象,同时,相对应在提供的时间 LocalDateTime目的。
package org.igi.theitroad;
import java.sql.Timestamp;
import java.time.LocalDateTime;
public class ConvertLocalDataTimeToTimestamp {
public static void main(String[] args) {
LocalDateTime current_date_time = LocalDateTime.now();
//returns time and date object of today's date.
//printing the time and date
System.out.println("Local Date Time : " + current_date_time);
//Timestamp object
Timestamp timestamp_object = Timestamp.valueOf(current_date_time);
System.out.println("Time stamp : " + timestamp_object);
}
}

