Skip to content

datetime

Using one DateFormat instance per thread with ThreadLocal

DateFormat with ThreadLocal

Here is a quick tip how to use DateFormat inside a ThreadLocal field.
Why do we need that? The reason is the DateFormat class is not thread-safe but creating its instances is an expensive operation. So, this is kind of a workaround that creates only one instance of DateFormat per thread.

package com.imsavva.test;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Savva Kodeikin
 */
public class ThreadLocalDateFormatTest   {

    private static ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("dd/MM/yyyy");
        }
    };

    public String formatDate(Date date) {
        return dateFormat.get().format(date);
    }
}

Parsing a date string to ISO8601 with Joda Time

Recently, I faced a date conversion task: convert a string date “yyyy-MM-ddZ” (i.e. “1983-09-15+03:00”) to the ISO8601 standard “yyyy-MM-dd’T’HH:mm:ss.SSSZ” (i.e. “1983-09-15T03:00:00.000+03:00”).

I used Apache Joda time to convert date. First, add a Maven dependency in pom.xml

<!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.9.4</version>
</dependency>

Read More →