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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong

Trending

  • How to Build Your Own AI SRE From Scratch
  • Running a Self-Hosted WAF in Production: Practical Lessons From SafeLine
  • How to Migrate From C/C++ to Rust: A Practical Guide for Embedded IoT Systems
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Jul. 25, 19 · Analysis
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
34.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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