Convert Date to String in Java is a continuation of the previous post. Here we show you how to convert date to string in java by creating a complete example program.
Let’s begin to create example program for Date to String conversion:
In this example I am taking current date via Calendar instance as an input and converting into a String. We will get the output String in various format too.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
package com.javabycode.date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class DateToStringExample { public static void main(String args[]) { Calendar cal = GregorianCalendar.getInstance(); Date today = cal.getTime(); DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); DateFormat df2 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); DateFormat df3 = new SimpleDateFormat("dd-MMM-yyyy"); DateFormat df4 = new SimpleDateFormat("MM dd, yyyy"); DateFormat df5 = new SimpleDateFormat("E, MMM dd yyyy"); DateFormat df6 = new SimpleDateFormat("E, MMM dd yyyy HH:mm:ss"); DateFormat df7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { // format() method formats a Date into a date/time string. String dateStr = df.format(today); System.out.println("String in dd/MM/yyyy format is: " + dateStr); String str2 = df2.format(today); System.out.println("String in dd-MM-yyyy HH:mm:ss format is: " + str2); String str3 = df3.format(today); System.out.println("String in dd-MMM-yyyy format is: " + str3); String str4 = df4.format(today); System.out.println("String in MM dd, yyyy format is: " + str4); String str5 = df5.format(today); System.out.println("String in E, MMM dd yyyy format is: " + str5); String str6 = df6.format(today); System.out.println("String in E, MMM dd yyyy HH:mm:ss format is: " + str6); String str7 = df7.format(today); System.out.println("String in yyyy-MM-dd format is: " + str7); } catch (Exception ex) { ex.printStackTrace(); } } } |
Run above main and the output will display like this:
Now, I share with you a complete code of Date to String conversion. The below function converts a Date to a String. It is taking two parammeters as input, one is Date object and the other is format string so you can custom your format as you want.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/** * * @param date Date object * @param format Format string * @return */ public String convertDateToString(Date date, String format) { String dateStr = null; DateFormat df = new SimpleDateFormat(format); try { dateStr = df.format(date); } catch (Exception ex) { System.out.println(ex); } return dateStr; } |
That’s it on the tutorial Convert Date to String in Java.