DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • A Spring Boot App With Half the Startup Time
  • Implementing the Planning Pattern With Java Enterprise and LangChain4j
  • Getting Started With Agentic Workflows in Java and Quarkus
  • Building AI-Powered Java Applications With Jakarta EE and LangChain4j

Trending

  • From 24 Hours to 2 Hours: How We Fixed a Broken BI System With Apache Airflow
  • The Big Data Architecture Blueprint: Core Storage, Integration, and Governance Patterns
  • Building AI-Powered Java Applications With Jakarta EE and LangChain4j
  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch
  1. DZone
  2. Coding
  3. Java
  4. Java SimpleDateFormat Is Not Simple

Java SimpleDateFormat Is Not Simple

Turns out, Java's SimpleDateFormat is not all that simple.

By 
Manjula Jayawardana user avatar
Manjula Jayawardana
·
Jul. 25, 19 · Analysis
Likes (15)
Comment
Save
Tweet
Share
34.6K Views

Join the DZone community and get the full member experience.

Join For Free

Formatting and parsing dates is a daily (painful) task. Every day, it gives us another headache.

A common way to format and parse dates in Java is using SimpleDateFormat. Here is a common class we can use.

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

public final class DateUtils {

    public static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    private DateUtils() {}

    public static Date parse(String target) {
        try {
            return SIMPLE_DATE_FORMAT.parse(target);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String format(Date target) {
        return SIMPLE_DATE_FORMAT.format(target);
    }

}


Do you think this is working as we expect? Let's try it.

    private static void testSimpleDateFormatInSingleThread() {
        final String source = "2019-01-11";
        System.out.println(DateUtils.parse(source));
    }

    // Fri Jan 11 00:00:00 IST 2019


Yes, it worked. Let's try it with more threads.

    private static void testSimpleDateFormatWithThreads() {
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        final String source = "2019-01-11";

        System.out.println(":: parsing date string ::");
        IntStream.rangeClosed(0, 20)
                .forEach((i) -> executorService.submit(() -> System.out.println(DateUtils.parse(source))));

        executorService.shutdown();
    }


Here is the result I got.

 :: parsing date string ::

... omitted

Fri Jan 11 00:00:00 IST 2019Sat Jul 11 00:00:00 IST 2111Fri Jan 11 00:00:00 IST 2019... omittedYes, it worked. Let's try it with more threads. 

Interesting result, isn't it? This is a common mistake most of us have made when formatting dates in Java. Why? because we are not aware of thread safety. Here is what the Java doc says about SimpleDateFormat:

"Date formats are not synchronized.
It is recommended to create separate format instances for each thread.
If multiple threads access a format concurrently, it must be synchronized
externally."
Tip: When we use instance variables, we should always check whether it is a thread safe class or not.

As the doc says, we can solve this by having separate instances for each thread. What if we want to share it? What are the solutions?

Solution 1: ThreadLocal

This can be solved by using a ThreadLocal variable.  ThreadLocal's get() method will give us the correct value for the current thread.

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

public final class DateUtilsThreadLocal {

    public static final ThreadLocal SIMPLE_DATE_FORMAT = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));

    private DateUtilsThreadLocal() {}

    public static Date parse(String target) {
        try {
            return SIMPLE_DATE_FORMAT.get().parse(target);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String format(Date target) {
        return SIMPLE_DATE_FORMAT.get().format(target);
    }

}


Solution 2: Java 8 Thread-Safe Date-Time API

Java 8 came with a new date-time API. We have a better alternative to SimpleDateFormat with less trouble. If we really need to stick with SimpleDateFormat, we can go ahead with ThreadLocal. But when we have a better option, we should consider using it.

Java 8 comes with several thread-safe date classes.

And here is what the Java docs say:

"This class is immutable and thread-safe."

It is worth studying more about these classes, including DateTimeFormatter, OffsetDateTime, ZonedDateTime, LocalDateTime, LocalDate, and LocalTime.

Our solution:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DateUtilsJava8 {

    public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    private DateUtilsJava8() {}

    public static LocalDate parse(String target) {
        return LocalDate.parse(target, DATE_TIME_FORMATTER);
    }

    public static String format(LocalDate target) {
        return target.format(DATE_TIME_FORMATTER);
    }

}


Conclusion

Java 8 solution uses an immutable class, which is a good practice for solving multi-threading problems. Immutable classes are thread-safe by nature, so use them whenever possible.

Happy coding!

Java (programming language)

Published at DZone with permission of Manjula Jayawardana. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • A Spring Boot App With Half the Startup Time
  • Implementing the Planning Pattern With Java Enterprise and LangChain4j
  • Getting Started With Agentic Workflows in Java and Quarkus
  • Building AI-Powered Java Applications With Jakarta EE and LangChain4j

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook