Parse uncommon date strings in Ballerina

62 Views Asked by At

I need to parse a simple date string like Jan 1, 2000 into the Ballerina record time:Civil. How do I do that effectively in Ballerina?

1

There are 1 best solutions below

0
Kavindu Gimhan Zoysa On

By using the Ballerina regexp, we can parse the above date string as shown below.

import ballerina/time;
import ballerina/lang.regexp;
import ballerina/io;

public function main() {
    string date = "Jan 10, 2000";
    io:println(civilFromAnciC(date));
}

function civilFromAnciC(string date) returns time:Civil|error {
   string[] dateComponents = regexp:split(re ` `, date.trim());
   int year = check int:fromString(dateComponents[2]);
   int month = monthToIndex(dateComponents[0]);
   string dayWithComma = dateComponents[1];
   int day = check int:fromString(dayWithComma.substring(0, dayWithComma.length() - 1));
 
   return {year, month, day, hour: 0, minute: 0};
}

function monthToIndex(string month) returns int {
    match month.toLowerAscii() {
        "jan" => { return 1; }
        "feb" => { return 2; }
        "mar" => { return 3; }
        "apr" => { return 4; }
        "may" => { return 5; }
        "jun" => { return 6; }
        "jul" => { return 7; }
        "aug" => { return 8; }
        "sep" => { return 9; }
        "oct" => { return 10; }
        "nov" => { return 11; }
        "dec" => { return 12; }
        _ => { return 0; }
    }
}

This how to guide has detailed examples of different date formats.

https://stackoverflow.com/collectives/wso2/articles/73277351/a-guide-for-date-time-conversion-in-ballerina-language