Spring boot - how to format time and store it in the database with the format HH:mm instead of HH:mm:ss format?

821 Views Asked by At

I work in a spring boot/angular application and I'm trying to send a time type attribute to my rest API with "HH: mm" format instead of "HH:mm: ss" format.

From the back-end application (Spring boot), i have this entity (i work with MySQL database):

    @Entity
    public class School implements Serializable {
       @Id
       @GeneratedValue(strategy = GenerationType.IDENTITY)
       @Column(nullable = false, updatable = false)
       private Long id;
       private String name;
       @Temporal(TemporalType.TIME)
       @DateTimeFormat(style = "HH:mm")
       @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="HH:mm")
       private Date o_date
    }

In the front-end application (angular), I use the p-calendar of primeng, when I send the time value from front-end to back-end everything works fine but when the time value comes from the back-end, it does not display on the front-end because it contains the seconds. So, what I want is that the time that is stored on the database is only HH:mm format and not HH:mm:ss.

Here's my form :

    <div class="field col">
        <label for="h_ouv">Opening time </label>
        <p-calendar id="o_time" [(ngModel)]="school.o_time" required [timeOnly]="true" dataType="string" [hourFormat]="24"></p-calendar>
    </div>

Note : I don't need to display the seconds and I don't want the user to select the seconds when setting the time.

UPDATE

I've resolved the problem by editing the getter of the time attribute.

public Date getO_date() throws ParseException {
    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
    String new_date = dateFormat.format(o_date);
    o_date = (Date)dateFormat.parse(new_date);
    return o_date;
}

As you have understood, I first converted the time (with the format HH:mm:ss) returned by mysql into a string, then the resulting string into a time but with the format I wanted (HH:mm ). Therefore, this value will be sent to the REST API. I hope it could help others and that I made myself understood because my English is not good

1

There are 1 best solutions below

3
On

you can use a different date util library to prase and format the date string that you are getting from the backend. like: date-fns. you can find a lot of different examples there.

But if you don't want to add any library this is the basic example.

const d = new Date('2021-01-19 03:14:07');
document.getElementById("demo").innerHTML = `${d.getFullYear()}-${d.getMonth()+1}-${d.getDate()} ${d.getHours()}:${d.getMinutes()}`;
<p id="demo"></p>