1

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

PT15
  • 13
  • 6
  • 1
    MM is for the month. Use mm for minutes. – Mar-Z Apr 20 '23 at 15:04
  • 1
    check [documentation](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/text/SimpleDateFormat.html) about meaning of `MM`, also having `HH` with `a` is wrong - BTW better stop using outdated classes like `Date`, `Calendar`, `SimpleDateFormat`. The *new* (Java 8, 2014!) classes from the `java.time` package are recommended instead – user16320675 Apr 20 '23 at 15:05
  • I strongly recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Apr 20 '23 at 16:32
  • While this question doesn’t seem to be an exact duplicate, there are many related questions, for example [here](https://stackoverflow.com/questions/18734452/display-current-time-in-12-hour-format-with-am-pm) and [here](https://stackoverflow.com/questions/50449169/converting-string-to-time-using-simpledateformat-issues). Under those questions please see the answers that are using java.time and not the old `SimpleDateFormat`. – Ole V.V. Apr 20 '23 at 16:37
  • Thanks @user16320675, will keep in mind – PT15 Apr 28 '23 at 10:12

1 Answers1

2

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
WJS
  • 36,363
  • 4
  • 24
  • 39