Skip to content
Related Articles

Related Articles

Improve Article

Change Gregorian Calendar to SimpleDateFormat in Java

  • Difficulty Level : Easy
  • Last Updated : 10 Aug, 2021

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: 
 

Java




// Java program to convert
// GregorianCalendar to SimpleDateFormat
 
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
 
public class GregorianCalendarToCalendar {
 
    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 calendar 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);
    }
}
Output: 
Gregorian date: Wed Apr 03 05:21:17 UTC 2019
SimpleDateFormat: 03-Apr-2019

 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :