springduration

How to change the format of a Duration?


I have a Spring API that lets me create and return a list of calls. A call has a duration (can be in seconds, minutes or hours) so I used the type Duration in my API and the type Interval in my Postgres database.

I am able to create a call with no problem as well as return the list of all calls but the duration is displayed in this format: PT15S for 15 seconds, PT5M30S for 5 minutes and 30 seconds for example.

It does the job but I would like to display it in a better format: 15s or 00:05:30 for example. I couldn't find a clear answer on where and how exactly to do this without having to change the type (I would like to keep Duration in both my entity and my DTO).

public class MyCallEntity {

    @Id
    @Column(name = "id", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "date", nullable = false)
    private Instant date;

    @Type(PostgreSQLIntervalType.class)
    @Column(name = "duration", columnDefinition = "interval", nullable = false)
    private Duration duration;
}


public class MyCallDto {
    private Long id;
    private Instant date;
    private Duration duration;
}

I tried using the @JsonFormat annotation with pattern HOURS, MINUTES and SECONDS: @JsonFormat(pattern = "MINUTES") but this doesn't do anything, I keep getting PT15S whenever I display the list of all calls or just one call.

Is there a way to do this without having to change the type at some point?


Solution

  • Try this in your dto:

    public class MyCallDto {
      //...
      private Duration duration;
      
      @JsonGetter("duration")
      public long getDurationInMinutes() {
        return duration.toMinutes();
      }
      
      @JsonSetter("duration")
      public void DurationInMinutes(long duration) {
        this.duration= Duration.ofMinutes(duration);
      }
    }
    

    Have a look on this https://www.baeldung.com/jackson-annotations If you want to get more informations about that implementation.