Skip to content
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms and Conditions
  • Author Profile: Govind

Simplified Learning Blog

Learning made easy

  • Java
    • Core Java Tutorial
    • Java 8
    • What is Rest API in java
    • Spring Framework
    • Type Casting in Java | 2 types Implicit and explicit casting
    • Spring Boot Tutorial
      • Spring Boot Rest API Example complete guide
    • Top 50 Java Interview Questions
    • JUnit 5 Tutorial
      • Assertall in JUnit 5
      • Assertions in JUnit 5
    • Java Thread Tutorials
      • How to create thread in Java
      • Multithreading in java
      • Daemon Thread in Java | How to create daemon thread in java
      • Top 40+ Multithreading interview questions
  • AWS
    • What is AWS (Amazon Web Services)
    • AWS IAM (Identity and Access Management)
    • AWS SNS | What is SNS
    • What is SQS | AWS SQS (Simple Queue Service)
    • What is AWS Lambda
    • Top 10 AWS Lambda interview questions
  • Java Codes
  • Software Architecture
    • Software Architecture Performance
    • Performance Principles of Software Architecture
    • System Performance Objective
  • Spring Boot Tutorial
  • Tools
    • JSON Formatter & Debugging Guide for Spring Boot Developers
    • Free Character Counter Tool: The Ultimate Guide to Counting Characters, Words, and Text Statistics
  • Tech Blogs
    • Java 21 New Features
    • Is Java Dead? Is java dead, 2023 ?
    • New Features in Java 17
  • Toggle search form

Java util date to String

Posted on March 31, 2023November 22, 2025 By Govind No Comments on Java util date to String

Java util date to String Conversion

In this tutorial will see how to convert date object to string objects in java. To convert it, there are few ways to implement it. Using java.util.Date and Using java 8 time and date APIs.

Table of Contents

Toggle
  • Java util date to String Conversion
  • The Standard Approach: SimpleDateFormat
    • 1. Key Steps in the Process
    • 2. Formatting Pattern Symbols
    • 3. Code Example
  • Modern Approach (Java 8 and Later)
    • 1. Conversion to Modern API
    • 2. Key Advantages of DateTimeFormatter
  • java.util.Date to String
  • Converting Using Java 8 Date/Time API
  • FAQ
  • Java java.util.Date to String Conversion FAQs
    • 1. What is the single biggest problem with using SimpleDateFormat?
    • 2. Why is the Java 8 DateTimeFormatter approach recommended over SimpleDateFormat?
    • 3. How does the conversion process handle Time Zones?
    • 4. How can I change the language (locale) of the formatted String?
    • 5. Can I convert a String back into a Date object using the formatter?

Converting a java.util.Date object into a formatted String representation is a core task in Java, primarily handled by the java.text.SimpleDateFormat class. This process involves defining a specific pattern (the format) and then applying that pattern to the Date object.


The Standard Approach: SimpleDateFormat

The SimpleDateFormat class, found in the java.text package, is the standard tool for formatting dates in a locale-sensitive manner.

1. Key Steps in the Process

  1. Instantiate SimpleDateFormat: Create an instance of the class, passing the desired date and time pattern as a String argument.
  2. Call format(): Use the format(Date date) method on the SimpleDateFormat object. This method takes your Date object and returns the formatted String.

2. Formatting Pattern Symbols

The pattern String dictates the exact layout of the output. Here are the most common symbols used:

SymbolMeaningExample
yYearyyyy $\rightarrow$ 2025
MMonth in yearMM $\rightarrow$ 11; MMM $\rightarrow$ Nov; MMMM $\rightarrow$ November
dDay in monthdd $\rightarrow$ 22
HHour in 24-hour format (0-23)HH $\rightarrow$ 20
hHour in 12-hour format (1-12)h $\rightarrow$ 8
mMinute in hourmm $\rightarrow$ 57
sSecond in minutess $\rightarrow$ 26
aAM/PM markera $\rightarrow$ PM
zTime Zonez $\rightarrow$ IST

3. Code Example

Java

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

public class DateToStringConverter {

    public static void main(String[] args) {
        // 1. Get the current Date object
        Date currentDate = new Date(); 

        // Define a custom pattern: Year-Month-Day Hour:Minute:Second AM/PM
        String pattern = "yyyy-MM-dd hh:mm:ss a"; 
        
        // 2. Instantiate SimpleDateFormat with the pattern
        SimpleDateFormat formatter = new SimpleDateFormat(pattern); 

        // 3. Apply the format to the Date object
        String formattedString = formatter.format(currentDate); 
        
        System.out.println("Original Date: " + currentDate.toString());
        System.out.println("Formatted String: " + formattedString);
        
        // Example with Locale (e.g., French month names)
        SimpleDateFormat frenchFormatter = new SimpleDateFormat("dd MMMM yyyy", Locale.FRENCH);
        String frenchDate = frenchFormatter.format(currentDate);
        System.out.println("French Format: " + frenchDate);
    }
}

Modern Approach (Java 8 and Later)

While SimpleDateFormat works, it has known issues, particularly that it is not thread-safe, meaning the same formatter instance should not be used concurrently by multiple threads.

Java 8 introduced the java.time API, which includes the LocalDateTime, ZonedDateTime, and DateTimeFormatter classes that are immutable and thread-safe.

If you are working with modern Java, the recommended practice is to first convert the legacy java.util.Date to the modern API, and then format it.

1. Conversion to Modern API

A java.util.Date object represents an instant on the timeline. We convert it to an Instant and then map it to a specific time zone to get a ZonedDateTime.

Java

import java.time.ZonedDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class Java8Converter {
    public static void main(String[] args) {
        Date legacyDate = new Date(); 

        // 1. Convert legacy Date to ZonedDateTime
        ZonedDateTime zdt = legacyDate.toInstant()
                                      .atZone(ZoneId.systemDefault());

        // 2. Define the thread-safe formatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");

        // 3. Apply the format
        String formattedString = zdt.format(formatter); 
        
        System.out.println("Java 8 Formatted String: " + formattedString);
    }
}

2. Key Advantages of DateTimeFormatter

  • Thread Safety: The core benefit is that DateTimeFormatter instances can be shared safely across your entire application.
  • Built-in Styles: It offers predefined, localized format styles (e.g., DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)) that automatically adapt to the user’s locale without manual pattern definition.
  • Clarity: The separation of the date/time object (ZonedDateTime) from the formatter (DateTimeFormatter) leads to cleaner code.

Let’s see how to convert date to string in java

java.util.Date to String

First, we need to define the pattern we need to convert it to.

package com.slb.core.java;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class DateFormatter {
    private static final String DATE_FORMAT = "MMM d, yyyy HH:mm a";
    private static final String EXPECTED_DATE_STRING_FORMAT = "Mar 1, 2018 12:00 PM";

    public static void main(String[] args) {

        TimeZone.setDefault(TimeZone.getTimeZone("IST"));
        Calendar calendar = Calendar.getInstance();
        calendar.set(2018, Calendar.MARCH, 1, 12, 0);
        Date date = calendar.getTime();

        DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);

        String formattedDate = formatter.format(date);

        assertEquals(EXPECTED_DATE_STRING_FORMAT , formattedDate);
        System.out.println(formattedDate);
    }
}

In the above code snippet, we are using simpleDateFormatter to format the date.

O/P

Mar 1, 2018 12:00 PM

Process finished with exit code 0

Converting Using Java 8 Date/Time API

Let’s see how to convert string to java util date in java 8. We will make java 8’s date and time API to format the date. Checkout JAVA8 tutorials here.

package com.slb.core.java;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class DateFormatter {
    private static final String DATE_FORMAT = "MMM d, yyyy HH:mm a";
    private static final String EXPECTED_DATE_STRING_FORMAT = "Mar 1, 2023 12:00 PM";

    public static void main(String[] args) {

        TimeZone.setDefault(TimeZone.getTimeZone("IST"));
        Calendar calendar = Calendar.getInstance();
        calendar.set(2023, Calendar.MARCH, 1, 12, 0);
        Date date = calendar.getTime();

        DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);

        String formattedDate = formatter.format(date);

        assertEquals(EXPECTED_DATE_STRING_FORMAT , formattedDate);
        System.out.println(formattedDate);


        //using java 8
        DateTimeFormatter formatterJava8Example = DateTimeFormatter.ofPattern(DATE_FORMAT);
        Instant instant = date.toInstant();
        LocalDateTime localDateTime = instant.atZone(ZoneId.of("UTC"))
                .toLocalDateTime();

        String formattedDateJava8 = localDateTime.format(formatterJava8Example);
        System.out.println(formattedDateJava8);

    }
}
O/P
Mar 1, 2023 12:00 PM
Mar 1, 2023 06:30 AM

Process finished with exit code 0

FAQ

Java java.util.Date to String Conversion FAQs

These FAQs address common issues and best practices related to formatting date objects in Java, focusing on the transition from the legacy java.util.Date and SimpleDateFormat to the modern java.time API.


1. What is the single biggest problem with using SimpleDateFormat?

The major issue is that java.text.SimpleDateFormat is not thread-safe.

If multiple threads try to use the same SimpleDateFormat instance concurrently (e.g., in a web server or multi-threaded application) to format or parse dates, it can lead to corrupted output, incorrect results, or unexpected exceptions. This requires developers to either create a new instance for every use or manage thread-local instances, adding significant boilerplate.

2. Why is the Java 8 DateTimeFormatter approach recommended over SimpleDateFormat?

The modern approach, utilizing java.time.format.DateTimeFormatter, is strongly recommended because it is immutable and thread-safe.

You can safely define a single DateTimeFormatter instance once and share it across all threads in your application. Additionally, the java.time API offers clearer distinction between date, time, and timezone objects (LocalDate, LocalTime, ZonedDateTime), eliminating many of the subtle bugs inherent in the legacy Date and Calendar classes.

3. How does the conversion process handle Time Zones?

This is a critical distinction between the two APIs:

AspectLegacy (SimpleDateFormat)Modern (DateTimeFormatter)
Date Objectjava.util.Date has no concept of time zone. It represents a single moment in time (like UTC).ZonedDateTime holds the time, date, and time zone information explicitly.
FormattingThe SimpleDateFormat formatter defaults to the JVM’s default time zone unless explicitly set using setTimeZone().The DateTimeFormatter formats the date based on the time zone contained within the ZonedDateTime object it is given.

When converting a java.util.Date to a formatted String, you must be aware that the output time will reflect the timezone setting of the formatter or the machine itself.

4. How can I change the language (locale) of the formatted String?

Locale determines things like month names (e.g., “Nov” vs. “Noviembre”) and time separators.

  • Legacy: Pass a Locale object when instantiating the formatter:Javanew SimpleDateFormat("dd MMMM yyyy", Locale.FRENCH);
  • Modern: Use the withLocale() method on a DateTimeFormatter instance:JavaDateTimeFormatter.ofPattern("dd MMMM yyyy").withLocale(Locale.FRENCH);

5. Can I convert a String back into a Date object using the formatter?

Yes. Both the legacy and modern formatters are designed for two-way conversion:

  • Formatting (Date $\rightarrow$ String): Use the format() method.
  • Parsing (String $\rightarrow$ Date): Use the parse() method.

When parsing, the format string you use must exactly match the pattern of the input string, or it will throw a ParseException (legacy) or a DateTimeParseException (modern).

Checkout the complete example here at githib@SLB

Govind

For over 15 years, I have worked as a hands-on Java Architect and Senior Engineer, specializing in building and scaling high-performance, enterprise-level applications. My career has been focused primarily within the FinTech, Telecommunications, or E-commerce sector, where I’ve led teams in designing systems that handle millions of transactions per day.

Checkout my profile here : AUTHOR https://simplifiedlearningblog.com/author/

Related

Java Codes Tags:Converting Using Java 8 Date/Time API, Java util date to String

Post navigation

Previous Post: Java 21 New Features
Next Post: Java Text Blocks

More Related Articles

Java int to String Conversion: Performance Benchmarks & Memory Pitfalls Java Codes
String to Integer Conversion in Java | Java convert string to int Java Codes
jcalendar in java swing example Java Codes
Converting PDF to JSON in Java Top 3 ways to code: Java Codes
Calculate date of birth from age in jquery Java Codes
Java dice roll program Java Codes

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Java Virtual Threads (Project Loom) in Real Enterprise Applications
  • Free Character Counter Tool: The Ultimate Guide to Counting Characters, Words, and Text Statistics
  • Understanding Java Sealed Classes
  • Top 50 Java Coding Interview Questions and Answers (2025 Updated)
  • Java Record Class Explained: Simple, Immutable Data Carriers

Recent Comments

  1. Gajanan Pise on Performance Principles of Software Architecture

Copyright © 2025 Simplified Learning Blog.

Powered by PressBook Green WordPress theme