如何在 Java 中将日期转换为时间戳?


在 Java 中,可以使用 Timestamp 类将 Date 转换为 Timestamp。Timestamp 类位于 sql 包中。Date 仅存储日期值,而 Timestamp 存储日期和时间值。TIMESTAMP 数据类型用于包含日期和时间部分的值。TIMESTAMP 的范围为 UTC 时间的 '1970-01-01 00:00:01' 到 UTC 时间的 '2038-01-19 03:14:07'。

让我们深入探讨本文,了解如何使用 Java 编程语言来实现这一目标。

举几个例子

示例 1

  • 假设输入日期为 2023 年 05 月 01 日。

  • 则对应的时间戳为“2023-01-05 20:37:54.832”。

示例 2

  • 假设输入日期为“2021 年 04 月 16 日”

  • 则对应的时间戳为“2022-04-04 04:12:35.0”。

算法

  • 步骤 1 − 声明日期或从系统获取默认日期。

  • 步骤 2 − 使用 Timestamp 类将其转换为时间戳。

  • 步骤 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 类的构造函数接收 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){
	
      //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 编程语言将 Date 转换为 Timestamp 的不同方法。

更新于: 2023 年 5 月 4 日

5K+ 阅读量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.