我是靠谱客的博主 勤劳刺猬,最近开发中收集的这篇文章主要介绍java datetime转string,使用DateTimeFormatter将java.util.date转换为String,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

How can I convert a java.util.Date to String using

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

The Date object which i get is passed

DateTime now = new DateTime(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).

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

Date date = ...;

Instant instant = date.toInstant();

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));

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

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.

最后

以上就是勤劳刺猬为你收集整理的java datetime转string,使用DateTimeFormatter将java.util.date转换为String的全部内容,希望文章能够帮你解决java datetime转string,使用DateTimeFormatter将java.util.date转换为String所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(41)

评论列表共有 0 条评论

立即
投稿
返回
顶部