首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用阿拉伯语分析日期问题和Java中的常规日期

用阿拉伯语分析日期问题和Java中的常规日期
EN

Stack Overflow用户
提问于 2019-03-06 07:16:19
回答 3查看 332关注 0票数 5

我有一个日期转换功能,类似于:

代码语言:javascript
复制
public static LocalDate getLocalDateFromString(String dateString) {
    DecimalStyle defaultDecimalStyle = DateTimeFormatter.ISO_LOCAL_DATE.getDecimalStyle();
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE.withDecimalStyle(defaultDecimalStyle.withZeroDigit('\u0660'));
    LocalDate date = LocalDate.parse(dateString, dateTimeFormatter);
    return date;
}

对于٢٠١٩-٠٤-١٥这样的阿拉伯日期,它可以正常工作,但是当我传递一个正常日期(如2019-07-31 )时,它会抛出一个异常,因为格式化程序的类型不同:

代码语言:javascript
复制
Exception in thread "main" java.time.format.DateTimeParseException: Text '2019-07-31' could not be parsed at index 0

我无法控制所传递的日期,因为它是由用户传递的。

如何使用相同的函数解析这两个日期?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-03-06 08:44:53

知道你的弦

DateTimeFormatter对你来说不是很容易。我推测,这个选择可能有一个目的:如果您能够将自己置于预先知道要解析的字符串中使用哪种数字的情况下,情况会更好。你可以考虑一下:你能说服你的字符串的来源把这个信息传递给你吗?

尝一尝,采取相应的行动

如果没有,当然是有办法的。以下是低水平,但应该是一般性的。

代码语言:javascript
复制
public static LocalDate getLocalDateFromString(String dateString) {
    DateTimeFormatter dateFormatter = DateTimeFormatter.ISO_LOCAL_DATE;
    // Take a digit from dateString to determine which digits are used
    char sampleDigit = dateString.charAt(0);
    if (Character.isDigit(sampleDigit)) {
        // Subtract the numeric value of the digit to find the zero digit in the same digit block
        char zeroDigit = (char) (sampleDigit - Character.getNumericValue(sampleDigit));
        assert Character.isDigit(zeroDigit) : zeroDigit;
        assert Character.getNumericValue(zeroDigit) == 0 : zeroDigit;
        DecimalStyle defaultDecimalStyle = dateFormatter.getDecimalStyle();
        dateFormatter = dateFormatter
                .withDecimalStyle(defaultDecimalStyle.withZeroDigit(zeroDigit));
    }
    // If the examined char wasn’t a digit, the following parsing will fail;
    // but in that case the best we can give the caller is the exception from that failed parsing.
    LocalDate date = LocalDate.parse(dateString, dateFormatter);
    return date;
}

我们试试看:

代码语言:javascript
复制
    System.out.println("Parsing Arabic date string to  "
            + getLocalDateFromString("٢٠١٩-٠٤-١٥"));
    System.out.println("Parsing Western date string to "
            + getLocalDateFromString("2019-07-31"));

这个片段的输出是:

将阿拉伯日期字符串解析为2019-04-15将西部日期字符串解析为2019-07-31

票数 4
EN

Stack Overflow用户

发布于 2019-03-06 07:30:17

我认为更好的解决方案是重写类中的方法。

票数 0
EN

Stack Overflow用户

发布于 2019-03-06 08:13:52

两种形式

如果您期望传入字符串中的两种格式之一,则建立两个DateTimeFormatter对象,每种预期格式一个。

两者都试一试

尝试一个格式化程序,捕获DateTimeParseException。如果被扔了,试试另一个。如果第二个抛出,那么您就知道您收到了意外的错误输入。

如果您有两种以上的预期格式,请收集所有可能的DateTimeFormatter对象。循环集合,尝试每一个解析输入,直到其中一个不抛出解析异常。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55017576

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档