欢迎访问宙启技术站
智能推送

如何在Java中实现日期时间转换功能?

发布时间:2023-06-11 18:21:57

在Java中,日期时间转换功能十分常见,由于Java提供了Date、LocalDateTime、ZonedDateTime等类来处理日期时间,转换功能变得非常容易。本文将探讨Java中日期时间转换的各种方法。

1. 字符串转日期时间

Java中的日期时间一般都是以字符串的形式表示的,而将这些字符串转为相应的日期时间对象则需要借助Java提供的相应类。以将字符串转为Date为例:

String str = "2021-03-26 20:16:30";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse(str);

这里,我们通过SimpleDateFormat类指定了日期时间字符串的格式,然后使用parse方法将字符串转换为Date类型的对象。

同样的,我们也可以将字符串转为LocalDateTime或ZonedDateTime对象:

String str = "2021-03-26 20:16:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);

String str = "2021-03-26 20:16:30+08:00[Asia/Shanghai]";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssxxx['['VV']']");
ZonedDateTime zonedDateTime = ZonedDateTime.parse(str, formatter);

这里,我们使用DateTimeFormatter指定了日期时间字符串的格式,并通过相应的parse方法将字符串转换为指定类型的日期时间对象。

2. 日期时间转字符串

与将字符串转为日期时间相反,在Java中将日期时间对象转为字符串也需要使用相应类。以将Date对象转为字符串为例:

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = sdf.format(date);

同样的,我们也可以将LocalDateTime或ZonedDateTime对象转为字符串:

LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String str = dateTime.format(formatter);

ZonedDateTime zonedDateTime = ZonedDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssxxx['['VV']']");
String str = zonedDateTime.format(formatter);

在这里,我们也同样使用相应的类指定了日期时间字符串的格式,然后通过相应的format方法将日期时间对象转为字符串。

3. 时间戳转日期时间

与字符串转日期时间或日期时间转字符串一样,在Java中将时间戳(以毫秒为单位的long类型数据)转为相应的日期时间对象也需要借助相应类。以将时间戳转为Date为例:

long timestamp = System.currentTimeMillis();
Date date = new Date(timestamp);

这里,我们直接将时间戳传入Date的构造方法中,便可获得相应的Date对象。

同样的,我们也可以将时间戳转为LocalDateTime或ZonedDateTime对象:

long timestamp = System.currentTimeMillis();
Instant instant = Instant.ofEpochMilli(timestamp);
LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());

long timestamp = System.currentTimeMillis();
Instant instant = Instant.ofEpochMilli(timestamp);
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Asia/Shanghai"));

在这里,我们使用Instant将时间戳转为相应的时间点对象,然后运用LocalDateTime或ZonedDateTime将该时间点对象转为指定类型的日期时间对象。

4. 日期时间转时间戳

在Java中将日期时间对象转为时间戳同样十分容易,只需要将日期时间对象转为Instant对象,然后再通过Instant的toEpochMilli方法获取时间戳即可。以将Date对象转为时间戳为例:

Date date = new Date();
long timestamp = date.getTime();

同样的,我们也可以将LocalDateTime或ZonedDateTime对象转为时间戳:

LocalDateTime dateTime = LocalDateTime.now();
Instant instant = dateTime.atZone(ZoneId.systemDefault()).toInstant();
long timestamp = instant.toEpochMilli();

ZonedDateTime zonedDateTime = ZonedDateTime.now();
Instant instant = zonedDateTime.toInstant();
long timestamp = instant.toEpochMilli();

在这里,我们使用相应的类将日期时间对象转为Instant对象,然后通过toEpochMilli方法将该时间点对象转为时间戳。

综上所述,Java中的日期时间转换操作十分方便,只需要注意指定好相应的日期时间格式就能够轻松实现日期时间转换。