java.util.date to String using DateTimeFormatter

痞子三分冷 提交于 2019-12-05 13:38:35

问题


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

回答1:


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

Or use the predefined formatter, DateTimeFormatter.ISO_LOCAL_DATE_TIME.

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.




回答2:


DateTime dt = new DateTime(date);
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss");
dt.toString(dtf)



回答3:


You can use the joda time formatter class:

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
# conflict with import java.time.format.DateTimeFormatter;

final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss")
            .withZone(DateTimeZone.UTC);

    System.out.println(DateTime.now().toString(formatter));



回答4:


since I asume you are using joda API: ergo, DateTimeFormatter is comming from org.joda.time.format.DateTimeFormatter:

 String dateTime = "02-13-2017 18:20:30";
// Format for input
DateTimeFormatter dtf = DateTimeFormat.forPattern("MM-dd-yyyy HH:mm:ss");
// Parsing the date
DateTime jodatime = dtf.parseDateTime(dateTime);

System.out.println(jodatime );



回答5:


DateTimeFormatterOBJECT=DateTimeFormatter.ofPattern("DD/MMM/YYYY HH//MM/SS");

String MyDateAndTime= LocalDate.now().format(DateTimeFormatterOBJECT);


来源:https://stackoverflow.com/questions/42210257/java-util-date-to-string-using-datetimeformatter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!