使用DateTimeFormatter将java.util.date转换为String [英] java.util.date to String using DateTimeFormatter

查看:1544
本文介绍了使用DateTimeFormatter将java.util.date转换为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用

 DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss")

我得到的Date对象被传递

The Date object which i get is passed

DateTime now = new DateTime(date);


推荐答案

如果您使用的是Java 8,则不应使用首先 java.util.Date (除非您从无法控制的库中收到 Date 对象结束)。

If you are using Java 8, you should not use java.util.Date in the first place (unless you receive the Date object from a library that you have no control over).

在任何情况下,您都可以将日期转换为 java。 time.Instant 使用:

In any case, you can convert a Date to a java.time.Instant using:

Date date = ...;
Instant instant = date.toInstant();

因为你只对日期和时间感兴趣,没有时区信息(我假设一切都是UTC) ,您可以将该瞬间转换为 LocalDateTime 对象:

Since you are only interested in the date and time, without timezone information (I assume everything is UTC), you can convert that instant to a LocalDateTime object:

LocalDateTime ldt = instant.atOffset(ZoneOffset.UTC).toLocalDateTime();

最后你可以用以下方式打印:

Finally you can print it with:

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
System.out.println(ldt.format(fmt));

或者使用预定义的格式化程序, DateTimeFormatter.ISO_LOCAL_DATE_TIME

Or use the predefined formatter, DateTimeFormatter.ISO_LOCAL_DATE_TIME.

System.out.println(ldt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

请注意,如果您不提供格式化程序,请调用 ldt.toString 以标准 ISO 8601 格式(包括毫秒)提供输出 - 您可以接受。

Note that if you don't provide a formatter, calling ldt.toString gives output in standard ISO 8601 format (including milliseconds) - that may be acceptable for you.

这篇关于使用DateTimeFormatter将java.util.date转换为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆