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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Using Python Libraries in Java
  • Designing a Java Connector for Software Integrations
  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs

Trending

  • Optimizing Integration Workflows With Spark Structured Streaming and Cloud Services
  • The Role of Functional Programming in Modern Software Development
  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  • My LLM Journey as a Software Engineer Exploring a New Domain
  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
33.9K 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

  • Using Python Libraries in Java
  • Designing a Java Connector for Software Integrations
  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!