【问题标题】:JodaTime: format date with 1st, 2nd, 3rd, etc. dayJodaTime:用第一天、第二天、第三天等格式化日期
【发布时间】:2012-10-08 15:50:07
【问题描述】:

JodaTime 是否提供此功能?在文档中找不到,也许我错过了什么? Formatting API doc 没有显示这样的功能。

如果不是,什么,解析结果字符串并匹配日期,相应地附加 st,nd,th?

看起来很老套,认为像 JodaTime 这样全面而精彩的库(它确实很摇滚 ;-))会提供这个看似简单的功能。

【问题讨论】:

    标签: scala jodatime


    【解决方案1】:

    虽然 Joda 不直接实现这一点,但您不需要外部库,只需求助于这样的简单实现即可。

    /**
     * Returns the correct suffix for the last digit (1st, 2nd, .. , 13th, .. , 23rd)
     */
    public static String getLastDigitSufix(int number) {
        switch( (number<20) ? number : number%10 ) {
            case 1 : return "st";
            case 2 : return "nd";
            case 3 : return "rd";
            default : return "th";
        }
    }
    

    响应 MHaris,上面的代码产生

    for (int i = 0; i < 99; i++) {
        System.out.print(i + getLastDigitSufix(i) + ", ");
    }
    
    0th, 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 
    10th, 11th, 12th, 13th, 14th, 15th, 16th, 17th, 18th, 19th, 
    20th, 21st, 22nd, 23rd, 24th, 25th, 26th, 27th, 28th, 29th, 
    30th, 31st, 32nd, 33rd, 34th, 35th, 36th, 37th, 38th, 39th, 
    40th, 41st, 42nd, 43rd, 44th, 45th, 46th, 47th, 48th, 49th, 
    50th, 51st, 52nd, 53rd, 54th, 55th, 56th, 57th, 58th, 59th, 
    60th, 61st, 62nd, 63rd, 64th, 65th, 66th, 67th, 68th, 69th, 
    70th, 71st, 72nd, 73rd, 74th, 75th, 76th, 77th, 78th, 79th, 
    80th, 81st, 82nd, 83rd, 84th, 85th, 86th, 87th, 88th, 89th, 
    90th, 91st, 92nd, 93rd, 94th, 95th, 96th, 97th, 98th, 99th
    

    根据English Ordinals in Wikipedia 看来是正确的。

    【讨论】:

    • 你也可能因为简单的实现错误而被否决——这段代码 sn-p 产生“11st”、“12nd”和“13rd”,所有这些都应该有后缀“th”。我会编辑帖子,但队列显然已满。
    • @MHarris 很高兴你没有编辑。看起来不错,自己检查! :)
    • 哦,非常好!看起来很棒,我的坏。 :-)
    【解决方案2】:

    看看PrettyTime,它建立在 JodaTime 之上。

    【讨论】:

    • +1 但是,伙计,我只是想把这个项目弄出去,不要向我扔更多的部门;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多