Subtract time fields

Hi all,

I am looking for a way to subtract two time fields (endTime - startTime) in orde to get the hours spend. Ik checked the forum and the documentation, but i can not seem to find anything suitable. Can someone point me out in the right direction?

Regards,

LS.

Hi.
You can create an attribute with @Transient and @MetaProperty annotations (see information here and here) and create a getter for this attribute using information from here.

For example:

   @Transient
    private Long spentHours;

    public void setSpentHours(Long spentHours) {
        this.spentHours = spentHours;
    }

    @MetaProperty(related = "startTime,endTime")
    public Long getSpentHours() {
        if (startTime != null & endTime != null) {
            return (endTime.getTime()-startTime.getTime())/3600000;
        } else return 0L;
    }

Note, that in this case information will not be stored in DB.

Another way is to subscribe to ItemPropertyChangeEvent handler of instance container on Entity editor screen and calculate the spent hours every time the value of startDate or endDate field changed

    protected void calculateHours() {
        Long hours = (getEditedEntity().getEndTime().getTime()-getEditedEntity().getStartTime().getTime())/3600000;
        getEditedEntity().setSpentHours(hours);
    }

    @Subscribe(id = "demoDc", target = Target.DATA_CONTAINER)
    public void onDemoDcItemPropertyChange(InstanceContainer.ItemPropertyChangeEvent<Demo> event) {
         calculateHours();
    }

Thanks Natalia,

I went for the second option because the data must be stored in the DB. I think i was not clear in my first question. The timeIn and timeOut fields are not inserted at the same time. When user comes in the timeIn the record is created and the timeIn is filled. When the user leaves the same record is updated and the timeOut is filled in. At that time the spent time must be calculated.

Any further help is welcome.

LS

Hi,

Have you evaluated using EntityChangedEvent?
https://doc.cuba-platform.com/manual-7.2/entityChangedEvent.html

It triggers every time when the entity is modified (right after it’s saved to DB).
You can calculate any calculateable attribute here and assign it to the entity.

1 Like