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:
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 |
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); } } |
1 2 3 4 5 6 |
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 |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.