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:
- Get the Gregorian Date to be converted.
- Create an object of SimpleDateFormat that will store the converted date
- Now change the Gregorian Date into SimpleDateFormat using the format() method.
- 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 gregorian date in 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
Please Login to comment...