Thursday, June 23, 2022

How to Convert Date to String in Java

In most of the Java application it’s a very common requirement to print date in a required format. For that you do need to convert date to a String that is in the required format. In this post we’ll see options to convert java.util.Date to String in Java using both SimpleDateFormat class and using DateTimeFormatter class Java 8 onward.


Using SimpleDateFormat for conversion

Before Java 8, a tried and tested way to convert date to string in Java is to use SimpleDateFormat which also gives you an option to provide customized format.

SimpleDateFormat resides in java.text package and extends DateFormat class which is an abstract class. DateFormat class also provides predefined styles to format dates and times.

Here note that SimpleDateFormat is not thread safe so not safe to use in multi-threaded application with out proper synchronization. An alternative way is to use ThreadLocal class, see an example of how ThreadLocal can be used by storing separate instance of SimpleDateFormat for each thread here.

When you create a SimpleDateFormat object, you specify a pattern String. The contents of the pattern String determine the format of the date and time.

Let’s see an example to convert date to String using the given format.

In this example there is a method getFormattedDate() where pattern is passed as an argument. Date is converted to String using the passed pattern.

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

public class FormatDate {

 public static void main(String[] args) {
  FormatDate fd = new FormatDate();
  
  // For date in format Wed, Jun 8, '16
  fd.getFormattedDate("EEE, MMM d, ''yy");

  // For date in format Wednesday, June 08, 2016
  fd.getFormattedDate("EEEE, MMMM dd, yyyy");

  // For date in format 05/08/2016
  fd.getFormattedDate("MM/dd/yyyy");

  // For date in format 08/05/2016
  fd.getFormattedDate("dd/MM/yyyy");
  
  // Only time like 21:52:14:096 PM
  // in 24 hr format, with mili seconds and AM/PM marker
  fd.getFormattedDate("HH:mm:ss:SSS a");

 }
 
 public void getFormattedDate(String pattern){
  Date today;
  String result;
  SimpleDateFormat formatter;
  // Creating the date format using the given pattern
  formatter = new SimpleDateFormat(pattern);
  // Getting the date instance
  today = new Date();
  // formatting the date
  result = formatter.format(today);
  System.out.println("Pattern: " + pattern + 
    " Formatted Date - " + result);
 }
}

Output

Pattern: EEE, MMM d, ''yy Formatted Date - Sun, Aug 13, '17
Pattern: EEEE, MMMM dd, yyyy Formatted Date - Sunday, August 13, 2017
Pattern: MM/dd/yyyy Formatted Date - 08/13/2017
Pattern: dd/MM/yyyy Formatted Date - 13/08/2017
Pattern: HH:mm:ss:SSS a Formatted Date - 12:50:14:097 PM

Using DateTimeFormatter class in Java 8 for conversion

From Java 8 there is another option to convert date to a string in Java. If you have an object of type LocalDate, LocalTime or LocalDateTime you can format it using the DateTimeFormatter class. All these classes are part of new Date & Time API in Java and reside in java.time package.

All these classes LocalDate, LocalTime or LocalDateTime have format method that takes object of DateFormatter class as argument. Using that object of DateFormatter, format for conversion can be provided.

You can use static methods ofLocalizedDate(FormatStyle dateStyle), ofLocalizedTime(FormatStyle dateStyle) or ofLocalizedDateTime(FormatStyle dateStyle) based on the type of object you are using to provide the pattern for formatting. Here FormatStyle is an Enumeration with the following Enum constants. Note that these methods return a locale specific date-time formatter.
  • public static final FormatStyle FULL- Full text style, with the most detail. For example, the format might be 'Tuesday, April 12, 1952 AD' or '3:30:42pm PST'.
  • public static final FormatStyle LONG- Long text style, with lots of detail. For example, the format might be 'January 12, 1952'.
  • public static final FormatStyle MEDIUM- Medium text style, with some detail. For example, the format might ' be 'Jan 12, 1952'.
  • public static final FormatStyle SHORT- Short text style, typically numeric. For example, the format might be '12.13.52' or '3:30pm'.

DateTimeFormatter Java Example

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

public class DateToString {

 public static void main(String[] args) {
  LocalDateTime curDateTime = LocalDateTime.now();
  System.out.println("Date before formatting " + curDateTime);
  String strDate =  getFormattedDate(curDateTime);
  System.out.println("Formatted date - " + strDate); 
 }
 
 private static String getFormattedDate(LocalDateTime dt){
  DateTimeFormatter df1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
  //DateTimeFormatter df1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
  //DateTimeFormatter df1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
  //DateTimeFormatter df1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
  return dt.format(df1);
 }
}

Output for FULL

Date before formatting 2017-08-13T20:08:25.056
Formatted date - Sunday, 13 August, 2017

Output for LONG

Date before formatting 2017-08-13T20:08:54.921
Formatted date - 13 August, 2017

Output for MEDIUM

Date before formatting 2017-08-13T20:09:27.308
Formatted date - 13 Aug, 2017

Output for SHORT

Date before formatting 2017-08-13T20:09:53.465
Formatted date – 13/8/17

Using ofPattern() method

You can also use ofPattern() method of the DateTimeFormatter class to provide the pattern for formatting. Using this method you can provide custom format while converting date to String in Java.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


public class DateToString {

 public static void main(String[] args) {
  LocalDateTime curDateTime = LocalDateTime.now();
  System.out.println("Date before formatting " + curDateTime);
  // Passing custom pattern
  getFormattedDate(curDateTime, "dd/MM/yyyy");
  //String strDate =  getFormattedDate(curDateTime);
  //System.out.println("Formatted date - " + strDate);
  
  getFormattedDate(curDateTime, "YYYY MMM dd");
  
  getFormattedDate(curDateTime, "MMMM dd yyyy hh:mm a");
 }

 private static void getFormattedDate(LocalDateTime dt, String pattern){
  DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);
  System.out.println("Formatted date " + " For Pattern " + pattern + " is "+ dt.format(df));
 }
}

Output

Date before formatting 2017-08-13T20:20:07.979
Formatted date  For Pattern dd/MM/yyyy is 13/08/2017
Formatted date  For Pattern YYYY MMM dd is 2017 Aug 13
Formatted date  For Pattern MMMM dd yyyy hh:mm a is August 13 2017 08:20 PM

That's all for this topic How to convert Date to String in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Convert String to Date in Java
  2. How to Convert Date And Time Between Different Time-Zones in Java
  3. Format Date in Java Using SimpleDateFormat
  4. How to Display Time in AM-PM Format in Java
  5. How to Find Last Modified Date of a File in Java

You may also like-

  1. How to Run javap Programmatically From Java Program
  2. How to Untar a File in Java
  3. Invoking Getters And Setters Using Reflection in Java
  4. Bounded Type Parameter in Java Generics
  5. Functional Interfaces in Java
  6. Difference Between CountDownLatch And CyclicBarrier in Java
  7. Difference Between equals() Method And equality Operator == in Java
  8. Interface Default Methods in Java

2 comments:

  1. Free easy & simple way to learn programming online we provide niit projects, assignments, cycle tests and much more..
    visit===>> http://foundjava.blogspot.in/

    ReplyDelete
  2. Anshudeep.

    Good morning! Wow your java stuff here is really awesome. Great work, much appreciated!!! May god bless you.
    No doubt this is the best blogging site for java, I can challenge anyone on this. It will be really helpful to many folks should you also blog other important topics of java like memory management, thread dump analysis, tuninigs, class loaders, gabage collection and design patterns. Eagerly waiting to see your posts on these topics. The way you try to explain and the content is really superb. Words not enough to thank you...

    ReplyDelete