Java 如何将日期转换为时间戳
在Java中,可以使用Timestamp类将日期转换为时间戳。Timestamp类位于sql包中。日期仅存储日期值,而时间戳存储日期和时间值。TIMESTAMP数据类型用于包含日期和时间部分的值。TIMESTAMP的范围是从’1970-01-01 00:00:01′ UTC到’2038-01-19 03:14:07′ UTC。
让我们深入探讨一下这篇文章,了解如何使用Java编程语言来实现它。
为您展示一些实例
实例-1
- 假设输入日期为05/01/2023。
-
那么相应的时间戳是“2023-01-05 20:37:54.832”。
实例-2
-
假设输入日期为“16/04/2021”。
-
那么相应的时间戳是“2022-04-04 04:12:35.0”。
步骤:
-
步骤1 - 声明日期或从系统中获取默认日期。
-
步骤2 - 使用时间戳类将其转换为时间戳。
-
步骤3 - 打印结果。
语法
getTime()方法 - 它返回自1970年1月1日00:00:00 GTM以来的毫秒数,该毫秒数由Date对象表示。
多种方法
我们提供了不同的方法来解决问题。
- 通过使用系统输入日期
-
通过使用字符串作为输入日期
让我们逐个看看程序及其输出。
方法1:通过使用系统输入日期
在这种方法中,我们从系统中获取输入日期。此外,Timestamp类的构造函数接收long值作为参数。因此,我们需要使用java.util.Date类的getTime()方法将日期转换为long值。
示例
import java.sql.Timestamp;
import java.util.Date;
public class Main {
//main method
public static void main(String args[]){
//getting the system date
Date date = new Date();
//getting the object of the Timestamp class
Timestamp tms = new Timestamp(date.getTime());
// printing the result
System.out.println(tms);
}
}
输出
2023-01-05 20:37:54.832
方法2:通过使用字符串作为输入日期
在这种方法中,我们将日期输入作为字符串。同时,Timestamp类的构造函数接收一个长整型值作为参数。因此,我们需要使用java.util.Date类的getTime()方法将日期转换成长整型值。
示例
import java.sql.Timestamp;
import java.util.Date;
public class Main {
// Main method
public static void main(String[] args){
//taking a string date
String date="2022/04/04 04:12:35";
//declaring timestamp
Timestamp ts=null;
//Intialize date with the string date
Date d=new Date(date);
// simple null check
if(d!=null){
// convert gettime from date and assign it to the timestamp
ts=new java.sql.Timestamp(d.getTime());
//printing the timestamp
System.out.println(ts);
}
}
}
输出
2022-04-04 04:12:35.0
在本文中,我们探讨了使用Java编程语言将日期转换成时间戳的不同方法。