解析 Ballerina 中不常见的日期字符串

Parse uncommon date strings in Ballerina

提问人:Kavindu Gimhan Zoysa 提问时间:8/30/2023 最后编辑:Kavindu Gimhan Zoysa 更新时间:9/8/2023 访问量:45

问:

我需要解析一个简单的日期字符串,例如 Ballerina 记录。 如何在芭蕾舞演员中有效地做到这一点?Jan 1, 2000time:Civil

日期格式芭蕾舞 女演员

评论


答:

0赞 Kavindu Gimhan Zoysa 9/8/2023 #1

通过使用 芭蕾舞女演员 ,我们可以解析上面的日期字符串,如下所示。regexp

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; }
    }
}

这有不同日期格式的详细示例。how to guide

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