Home > database >  Calandar class in java giving incorrect output
Calandar class in java giving incorrect output

Time:09-27

I am trying to determine if a day is a weekend or not based on a user entered date using the calandar class. but when I print out the value of the day I am getting incorrect output.

this is my code:

public static void function(String newDate){
SimpleDateFormat myFormat = new SimpleDateFormat("dd/mm/yyyy");
  Date date;
    try {
      date = myFormat.parse(newDate);
      System.out.println(date);
      Calendar cal = Calendar.getInstance();
       cal.setTime(date);
     System.out.println( cal.getTime());
      System.out.println(cal.get(Calendar.DAY_OF_WEEK));
      System.out.println(Calendar.MONDAY);
      System.exit(0);
    } catch (ParseException e2) {
      // TODO Auto-generated catch block
      e2.printStackTrace();
    }
}

this is being tested with input date 27/09/2021 which is an monday but the output is returning 4 instead of 2

System.out.println( cal.getTime());  is outputting `Wed Jan 27 00:09:00 AEDT 2021` which is incorrect 

But I believe the problem is stemming from this line date = myFormat.parse(newDate); as this also outputs Wed Jan 27 00:09:00 AEDT 2021

but newDate outputs 27/09/2021

CodePudding user response:

You can try to instantiate myFormat as:-

SimpleDateFormat myFormat = new SimpleDateFormat("dd/MM/yyyy");
  •  Tags:  
  • java
  • Related