Change Gregorian Calendar to SimpleDateFormat in Java

Given a date in GregorianCalendar format change it into SimpleDateFormat.

Examples:

Input: Sat Apr 28 13:36:37 UTC 2018
Output: 28-Apr-2018

Input: Wed Apr 03 20:49:45 IST 2019
Output: 03-Apr-2019

Approach:



  1. Get the Gregorian Date to be converted.
  2. Create an object of SimpleDateFormat that will store the converted date
  3. Now change the Gregorian Date into SimpleDateFormat using the format() method.
  4. This format method will take the only the date part of Gregorian date as the parameter. Hence using getTime() method, this required date is passed to format() method.

Below is the implementation of the above approach:

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to convert
// GregorianCalendar to SimpleDateFormat
  
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
  
public class GregorianCalenderToCalender {
  
    public static void convert(
        GregorianCalendar gregorianCalendarDate)
    {
        // Creating an object of SimpleDateFormat
        SimpleDateFormat formattedDate
            = new SimpleDateFormat("dd-MMM-yyyy");
  
        // Use format() method to change the format
        // Using getTime() method,
        // this required date is passed
        // to format() method
        String dateFormatted
            = formattedDate.format(
                gregorianCalendarDate.getTime());
  
        // Displaying grogorian date ia SimpleDateFormat
        System.out.print("SimpleDateFormat: "
                         + dateFormatted);
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Get the Gregorian Date to be converted.
        GregorianCalendar gcal = new GregorianCalendar();
        gcal.set(GregorianCalendar.YEAR, 2019);
  
        // In gregorian calender month is started from 0
        // so for april month will be 03 not 04
        gcal.set(GregorianCalendar.MONTH, 03);
  
        gcal.set(GregorianCalendar.DATE, 03);
  
        // Displaying Current Date
        // using GregorianCalendar Class
        System.out.println("Gregorian date: "
                           + gcal.getTime());
  
        // Function to convert this to SimpleDateFormat
        convert(gcal);
    }
}

chevron_right


Output:

Gregorian date: Wed Apr 03 05:21:17 UTC 2019
SimpleDateFormat: 03-Apr-2019


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.