Convert java.util.Date to String in yyyy-MM-dd format without creating a lot of objects

Oleksandr Riznyk :

I need to convert java.util.Date to String in yyyy-MM-dd format in a big amounts.

I have just moved to java 8 and want to know how to do it properly. My solution with Java 7 was like:

DateTimeFormatter DATE_FORMATTER = DateTimeFormat.forPattern(DATE_FORMAT_PATTERN)

DATE_FORMATTER.print(value.getTime())

It helped me not to create a lots of redundant objects.

So now when I moved to java 8 I want rewrite it properly but:

LocalDate.fromDateFields(value).toString())

creates each time new LocalDate object and this gives a lot of work to GC.

Are there any ways to solve my problem? Performance and thread-safety are very important.

After some testing I have found that even with creating new objects construction with:

new SimpleDateFormat("yyyy-MM-dd")).format(value)) 

the fastest all over this topic.

Joop Eggen :

The following only has an overhead for the conversion of the old Date to the new LocalDate.

    Date date = new Date();
    LocalDate ldate = LocalDate.from(date.toInstant().atZone(ZoneOffset.UTC));
    String s = DateTimeFormatter.ISO_DATE.format(ldate); // uuuu-MM-dd

It is true however that DateTimeFormatters are thread-safe and hence will have one instantiation more per call.

P.S.

I added .atZone(ZoneOffset.UTC) because of a reported exception, and @Flown's solution: specifying the zone. As Date is not necessarily used for UTC dates, one might use another one.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35620&siteId=1