How to use the SimpleDateFormat class to convert a Java Date to a formatted String?

JavaObject Oriented ProgrammingProgramming

The Java SimpleDateFormat class provides convert between a Java String to a Date or Date to String.

Example

import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class SimpleDateFormatTest {
   public static void main(String[] args) {
      // get today's date
      Date today = Calendar.getInstance().getTime();
      // create a date "formatter"
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
      // create a new String using the date format
      String formattedDate = formatter.format(today);
      // prints converted date to string format
      System.out.println(" Date is:" + formattedDate);
   }
}

Output

Date is:2019-06-04-05.55.13
raja
Published on 31-May-2019 20:08:47
Advertisements