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


Java 中,可以使用 Date类 将时间戳转换为日期。Date类位于 java.util包 中。Date类的构造函数接收一个长整型值作为参数。由于Date类的构造函数需要一个长整型值,我们需要使用**TimeStamp**类的**getTime()**方法将Timestamp对象转换为长整型值。

让我们深入研究这篇文章,了解如何使用Java编程语言来实现。

举个例子

假设时间戳是06/01/2023。

那么对应的日期是“2023年1月6日星期五 19:51:09 GMT”。

算法

算法 1(使用构造函数)

步骤1:从系统获取默认时间戳。

步骤2:使用currentTimeMillis将其传递给时间戳类的构造函数。

步骤3:现在将长整型值传递给Date类的构造函数。

步骤4:打印结果,即日期值。

算法 2(使用Date引用)

步骤1:从系统获取默认时间戳。

步骤2:直接将时间戳类的对象赋值给Date类,因为Date类是TimeStamp类的超类。

步骤3:打印结果,即日期值。

算法 3(使用Calendar类)

步骤1:从系统获取默认时间戳。

步骤2:获取Calendar类的实例。

步骤3:现在将长整型值传递给Calendar类的函数。

步骤4:使用getTime()函数获取时间

步骤5:打印结果,即日期值。

语法

setTimeMillis()方法:它是Calendar类的方法,用于以毫秒为单位设置当前时间。

getTime()方法:它返回自1970年1月1日00:00:00 GTM以来的毫秒数,该数由Date对象表示。

多种方法

我们提供了不同的解决方案。

  • 使用构造函数

  • 使用Date引用

  • 使用Calendar类

让我们一一查看程序及其输出。

方法1:使用构造函数

在此方法中,我们将使用java.util包提供的java.util.Date类,并使用此类的构造函数将时间戳转换为日期。

示例

import java.sql.Timestamp;
import java.util.Date;
public class Main {
	// Main method
	public static void main(String[] args)
	{
		//taking current time from system
		Timestamp tms = new Timestamp(System.currentTimeMillis());

		// Passing the value in the Date class constructor
		Date date = new Date(tms.getTime());

		// Printing the date value
		System.out.println(date);
	}
}

输出

Thu Aug 17 07:01:40 GMT 2023

方法2:使用Date引用

在此方法中,我们从系统获取日期输入。然后,我们使用java.util.date包的date类。并直接将时间戳类的对象赋值给Date类。

示例

import java.sql.Timestamp;
import java.util.Date;
public class Main {
	// Main method
	public static void main(String[] args)
	{
	   //taking current time from system
		Timestamp tms = new Timestamp(System.currentTimeMillis());

		//Direct assigning of object of timestamp class to date class
		Date date = tms;

		//Printing the date value
		System.out.println(date);
	}
}

输出

2023-08-17 07:04:03.359

方法3:使用Calendar类

在此方法中,我们从系统获取日期输入。然后,我们使用Calendar类从时间戳中获取日期。

示例

import java.sql.Timestamp;
import java.util.Date;
import java.util.Calendar;

public class Main {

	// Main method
	public static void main(String[] args)
	{
	   
	   //taking current time from system
		Timestamp ts = new Timestamp(System.currentTimeMillis());

		//Getting the calendar class instance
		Calendar calendar = Calendar.getInstance();

		// Passing the long value to calendar class function
		calendar.setTimeInMillis(ts.getTime());

		//printing the time using getTime() function
		System.out.println(calendar.getTime());
	}
}

输出

Thu Aug 17 07:05:15 GMT 2023

在这篇文章中,我们探讨了使用Java编程语言将时间戳转换为日期的不同方法。

更新于:2024年6月20日

10K+ 浏览量

启动你的职业生涯

通过完成课程获得认证

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