Search code examples
timeballerina

How to compare two 'time:Civil' values in Ballerina?


I'm encountering an issue in Ballerina when trying to compare two times represented as time:Civil. The error message I'm receiving is operator '<' not defined for 'ballerina/time:2.2.4:Civil' and 'ballerina/time:2.2.4:Civil'.

Can someone guide me on how to properly compare two times in Ballerina and resolve this error?


Solution

  • We can not compare two time:Civil values using < or >. We can convert them into time:Utc and compare them as in the example below.

    import ballerina/time;
    import ballerina/io;
        
    public function main() returns time:Error? {
        time:Civil utcToCivil1 = check time:civilFromString("2017-01-01T00:00:00Z");
        time:Civil utcToCivil2 = check time:civilFromString("2017-02-01T00:00:00Z");
        
        time:Utc utcFromCivil1 = check time:utcFromCivil(utcToCivil1);
        time:Utc utcFromCivil2 = check time:utcFromCivil(utcToCivil2);
        
        io:println(utcFromCivil1 < utcFromCivil2);
    }