How to Convert Date to String in Java

In this post, we will see how to convert date to string in java. It is more of utility which is mostly used while displaying dates in different string formats while generating any pdf or excel reports.You may also check how to convert string to date

Java program:

package org.arpit.java2blog;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
 
/**
 * SimpleDateFormat example: Convert from a Date to a formatted String
 *

 */
public class SimpleDateFormatExample
{
  public static void main(String[] args)
  {
    //  get today's date
    Date todayDate = Calendar.getInstance().getTime();
 
    //  we need to create format object here by specifying desired string format
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
 
    // create a new String using the date format we want
    String dateInStringFormat = formatter.format(todayDate);
     
    //  this prints date in required format 
    System.out.println("Date in format yyyy-MM-dd-hh.mm.ss = " + dateInStringFormat);
    
    // More examples:
    
    // Example 2
    formatter = new SimpleDateFormat("dd/MM/yyyy hh.mm.ss");
    dateInStringFormat = formatter.format(todayDate);
    System.out.println("Date in format dd/MM/yyyy hh.mm.ss = " + dateInStringFormat);
    
    // Example 3
    formatter = new SimpleDateFormat("yyyyMMdd");
    dateInStringFormat = formatter.format(todayDate);
    System.out.println("Date in format yyyyMMdd = " + dateInStringFormat);
    
    // Example 4
    formatter = new SimpleDateFormat("E, MMM dd yyyy");
    dateInStringFormat = formatter.format(todayDate);
    System.out.println("Date in format E, MMM dd yyyy = " + dateInStringFormat);
    
  }
}
When you run above program, you will get following output:
Date in format yyyy-MM-dd-hh.mm.ss = 2016-01-26-02.03.02
Date in format dd/MM/yyyy hh.mm.ss = 26/01/2016 02.03.02
Date in format yyyyMMdd = 20160126
Date in format E, MMM dd yyyy = Tue, Jan 26 2016


Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012