How can I change the date format in Java ?

How can I change the date format in Java ?

Asked on December 28, 2018 in Java.
Add Comment


  • 5 Answer(s)

    By using SimpleDateFormat one can convert format of date,

    final String OLD_FORMAT = "dd/MM/yyyy";
    final String NEW_FORMAT = "yyyy/MM/dd";
     
    // August 12, 2010
    String oldDateString = "12/08/2010";
    String newDateString;
     
    SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
    Date d = sdf.parse(oldDateString);
    sdf.applyPattern(NEW_FORMAT);
    newDateString = sdf.format(d);
    
    Answered on December 28, 2018.
    Add Comment

    Try to do this simple code,

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    sdf.format(new Date());
    
    Answered on December 28, 2018.
    Add Comment

    The SimpleDateFormat can be used for convert the format of date.

        String DATE_FORMAT = "yyyy/MM/dd";
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        System.out.println("Formated Date " + sdf.format(date));
    

    Here is an  Example:

    import java.text.SimpleDateFormat;
    import java.util.Date;
     
    public class JavaSimpleDateFormatExample {
        public static void main(String args[]) {
            // Create Date object.
            Date date = new Date();
            // Specify the desired date format
            String DATE_FORMAT = "yyyy/MM/dd";
            // Create object of SimpleDateFormat and pass the desired date format.
            SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
            /*
            * Use format method of SimpleDateFormat class to format the date.
            */
            System.out.println("Today is " + sdf.format(date));
        }
    }
    
    Answered on December 28, 2018.
    Add Comment

    // Setting the pattern SimpleDateFormat sm = new SimpleDateFormat(“mm-dd-yyyy”); // myDate is the java.util.Date in yyyy-mm-dd format // Converting it into String using formatter String strDate = sm.format(myDate); //Converting the String back to java.util.Date Date dt = sm.parse(strDate);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    sdf.format(new Date());
    Answered on January 16, 2019.
    Add Comment

    ‘M’ (Capital) represent month & ‘m’ (Simple) represent minutes

    Some example for months

    'M' -> 7  (without prefix 0 if it is single digit)
    'M' -> 12
    
    'MM' -> 07 (with prefix 0 if it is single digit)
    'MM' -> 12
    
    'MMM' -> Jul (display with 3 character)
    
    'MMMM' -> December (display with full name)

    Some example for minutes

    'm' -> 3  (without prefix 0 if it is single digit)
    'm' -> 19
    'mm' -> 03 (with prefix 0 if it is single digit)
    'mm' -> 19
    Answered on January 16, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.