Search code examples
javadatetimetimeformatsimpledateformat

SimpleDateFormat is giving wrong hours and seconds data


I'm using SimpleDateFormat to get the hours and seconds in this format "HH:MM a" for 2 dates in same function. The output printing is same for both of them and it is mostly of the first date. The code for it is as follows:

//to get the time
public static void getHourAndTime(Date startDate, Date endDate){
    
    SimpleDateFormat formatter = new SimpleDateFormat("HH:MM a");
    String formattedstartTime = formatter.format(startDate);
    System.out.println("startTime"+formattedstartTime);

    String formattedEndTime = formatter.format(endDate);
    System.out.println("endTime"+formattedEndTime);
}

Any solution/ reason for this would be helpful.

Edit: this was a piece of an old code in the application, that I was trying to change.

Thanks


Solution

  • Date and its methods are obsolete and buggy. Unless you must use Date I would use classes from the java.time package. Here is how the change would look by modifying your code. Note the change from 24 hour clock (HH) to 12 hour clock (hh) as pointed out by @OleV.V.

    getHourAndTime(LocalDateTime.now(), LocalDateTime.now().plusSeconds(600));
                
    
    public static void getHourAndTime(LocalDateTime startDate, LocalDateTime endDate) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("hh:mm a");
        System.out.println("startTime: " + startDate.format(dtf));
        System.out.println("endTime: " + endDate.format(dtf));
    }
    

    prints

    startTime: 11:53 AM
    endTime: 12:03 PM