MabutaBee
MabutaBee

Reputation: 57

Subtracting a two time values in ballerina

I'm trying to calculate the difference between two time values to get the difference in minutes in Ballerina.

Example

 If timeIn = 09:40:00 (HH:MM:SS)    and    timeOut = 09:55:00 (HH:MM:SS)

Then I want to get the difference of the two times such that:

timeDifference = timeOut - timeIn
timeDifference = 15 minutes

How can I achieve this in ballerina where my timeIn is the current time when a user logs in and the timeOut is the current time when the user logs out. how can I get the difference in minutes

Thank you

Upvotes: 0

Views: 121

Answers (2)

ycr
ycr

Reputation: 14574

One way to do this is to convert the two times into epoch time subtract and convert back to minutes. You can refer this for more information.

https://ballerina.io/learn/api-docs/ballerina/time.html

Ex : You can get the epoch time like below,

int timeValue = time.time;

Upvotes: 0

Anupama Pathirage
Anupama Pathirage

Reputation: 691

Here is a sample code which gives the difference in minutes.

import ballerina/time;
import ballerina/io; 

function main(string... args) {
  time:Time t1 = time:parse("09:40:00", "HH:mm:ss");
  time:Time t2 = time:parse("09:55:00", "HH:mm:ss");
  int timeDiffInMillSeconds = t2.time - t1.time;
  int timeDiffInMinutes = timeDiffInMillSeconds/60000;

  io:println(timeDiffInMinutes);
}

If you need to get the difference between two timestamps you can simply use currentTime function instead of parse() as follows.

import ballerina/time;
import ballerina/io; 

function main(string... args) {
  time:Time t1 = time:currentTime();
  time:Time t2 = time:currentTime();
  int timeDiffInMillSeconds = t2.time - t1.time;
  int timeDiffInMinutes = timeDiffInMillSeconds/60000;
  io:println(timeDiffInMillSeconds);
  io:println(timeDiffInMinutes);
}

Upvotes: 2

Related Questions