How can I utilize SimpleDateFormat with Calendar ?

How can I utilize SimpleDateFormat with Calendar ?

Asked on December 25, 2018 in Java.
Add Comment


  • 5 Answer(s)

    We can simply use this code,

    Calendar cal = new GregorianCalendar();
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    dateFormat.setTimeZone(cal.getTimeZone());
    System.out.println(dateFormat.format(cal.getTime()));
    
    Answered on December 25, 2018.
    Add Comment

    Insert this snippet in our actual code , we can utilize SimpleDateFormat with Calendar.

    Calendar cal = new GregorianCalendar();
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    #---- This uses the provided calendar for the output -----
    dateFormat.setCalendar(cal);
    System.out.println(dateFormat.format(cal.getTime()));
    
    Answered on December 25, 2018.
    Add Comment

    A function named Calendar.getTime() gives the Date and that can be used with SimpleDateFormat. So try to use that function.

    Answered on December 25, 2018.
    Add Comment

    Your code is wrong. No point of parsing date and keep that as Date object.

    You can format the calender date object when you want to display and keep that as a string.

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, 1);
    Date date = cal.getTime();             
    SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");          
    String inActiveDate = null;
    try {
        inActiveDate = format1.format(date);
        System.out.println(inActiveDate );
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    Answered on January 16, 2019.
    Add Comment
    Calendar cal = new GregorianCalendar();
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    dateFormat.setTimeZone(cal.getTimeZone());
    System.out.println(dateFormat.format(cal.getTime()));
    Answered on January 16, 2019.
    Add Comment


  • Your Answer

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