How to Convert Date to String in Java

Convert Date to String in Java

In this post, We will show you about, How to Convert Date to String in Java.

The below example program will give you idea about, How the Conversion happening between [su_highlight]java.util.Date[/su_highlight] to [su_highlight]java.lang.String[/su_highlight] using [su_highlight]java.text.DateFormat[/su_highlight] API`s.

DateToString.java

package com.dineshkrish.date;

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

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class DateToString {
	
	public static String convertDateToString(Date date, String format) {
		
		String convertedString = null;
		
		if((date != null) && (format != null && !format.isEmpty())) {
			
			// Defining the DateFormate Object by passing Format
			DateFormat dateFormat = new SimpleDateFormat(format);
		
			// Converting String to Date
			convertedString = dateFormat.format(date);
		}	
		
		return convertedString;
	}
	

	public static void main(String[] args) {
		
		System.out.println("How to Convert Date to String in Java");
		System.out.println("---------------------------------------");
		
		System.out.println(convertDateToString(new Date(), "dd/MM/yyyy"));
		System.out.println(convertDateToString(new Date(), "dd-MM-yyyy"));
		System.out.println(convertDateToString(new Date(), "dd.MM.yyyy"));
		
	}
}

Output

28/11/2016
28-11-2016
28.11.2016

References

1. Java API Documentation
2. java.util.Date API
3. java.text.DateFormat API