Java.util.date for string using DateTimeFormatter

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

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

The Date object that I get is passed

 DateTime now = new DateTime(date); 
+11
source share
5 answers

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

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

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

Since you are only interested in date and time without time zone information (I assume that everything is in UTC format), you can convert this moment 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 DateTimeFormatter.ISO_LOCAL_DATE_TIME formatter.

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

Please note that if you do not provide a formatter, calling ldt.toString will produce output in the standard ISO 8601 format (including milliseconds) - this may be acceptable to you.

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

You can use the formatter class:

 final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss") .withZone(DateTimeZone.UTC); System.out.println(DateTime.now().toString(formatter)); 
+1
source

since I use the joda: ergo API, DateTimeFormatter is sent 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 ); 
0
source
 DateTimeFormatterOBJECT=DateTimeFormatter.ofPattern("DD/MMM/YYYY HH//MM/SS"); String MyDateAndTime= LocalDate.now().format(DateTimeFormatterOBJECT); 
0
source

Source: https://habr.com/ru/post/1264176/


All Articles