使用Android中的Thai Calendar分析特定格式的日期

问题描述 投票:0回答:1

我需要以泰文本地格式解析日期(例如,应该将2019年返回为2562),但不知道该怎么做。当前使用SimpleDateFormatter解析默认本地格式的日期。

fun adjustTimePattern(dateString: String, oldPattern: String, newPattern: String): String? {
    val dateFormat = SimpleDateFormat(oldPattern, Locale.getDefault())
    dateFormat.timeZone = TimeZone.getTimeZone("UTC")
    return try {
        val calendar = Calendar.getInstance()
        calendar.time = dateFormat.parse(dateString)
        val newFormat = SimpleDateFormat(newPattern, Locale.getDefault())
        newFormat.format(calendar.time)
    } catch (e: ParseException) {
        return null
    }
}

[试图对区域设置的值进行硬编码(使用Locale("th", "TH")而不是Locale.getDefault()),但是由于SimpleDateFormat类使用格里高利日历本身而感到幸运。

也尝试过使用LocalDateDateTimeFormatter,但是年份值不会改变。

fun formatTime(pattern: String): String {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val formatter = DateTimeFormatter.ofPattern(pattern, Locale("th", "TH"))
        LocalDate.now().format(formatter)
    } else {
        ""
    }
}

有人可以帮我吗?

java android kotlin date-parsing thai
1个回答
0
投票

您可以使用java.time.chrono.ThaiBuddhistDate完成此操作,请参见以下示例:

public static void main(String[] args) throws ParseException {
    ThaiBuddhistDate tbd = ThaiBuddhistDate.now(ZoneId.systemDefault());
    System.out.println(tbd.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
}

我在系统上得到的输出是

2562-10-24
© www.soinside.com 2019 - 2024. All rights reserved.