Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 263
Oleksandr Riznyk Avatar asked Oct 18 '18 09:10

Oleksandr Riznyk


Video Answer


2 Answers

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.

like image 194
Joop Eggen Avatar answered Oct 17 '22 05:10

Joop Eggen


Use SimpleDateFormat to format Date.

watch out, SDF is NOT THREAD-SAFE, it might not be important but keep that in mind.

For Example:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println((sdf.format(new Date())).toString());

LINK with more information.

like image 3
Emil Hotkowski Avatar answered Oct 17 '22 04:10

Emil Hotkowski