如何在Groovy中将24小时格式转换为12小时格式

时间:2019-10-02 05:15:50

标签: groovy

我是groovy的新手,我想将24小时格式转换为12小时格式。它要使用什么代码?有内置的方法吗?

我只想要普通代码而不是Java代码

2 个答案:

答案 0 :(得分:1)

我认为这个问题有点类似于How to convert 24 hr format time in to 12 hr Format?。只是Java和Groovy具有许多相似之处。为了指出这一点,我从上述问题中得到了Cloud的答案,并将其转换为Groovy。

import java.time.LocalTime
import java.time.format.DateTimeFormatter

final String time = "21:49"

String result = LocalTime.parse(time, DateTimeFormatter.ofPattern("HH:mm")).format(DateTimeFormatter.ofPattern("hh:mm a"));

println(result)

如果要构建自己的时间功能,可以尝试自定义以下代码。

final String time = "21:49"

final String _24to12( final String input ){
    if ( input.indexOf(":") == -1 )  
        throw ("")

    final String []temp = input.split(":")

    if ( temp.size() != 2 )
        throw ("")  // Add your throw code
                    // This does not support time string with seconds

    int h = temp[0] as int  // if h or m is not a number then exception
    int m = temp[1] as int  // java.lang.NumberFormatException will be raised
                            // that can be cached or just terminate the program
    String dn

    if ( h < 0 || h > 23 )
        throw("")  // add your own throw code
                   // hour can't be less than 0 or larger than 24

    if ( m < 0 || m > 59 )
        throw("")  // add your own throw code 
                   // minutes can't be less than 0 or larger than 60

    if ( h == 0 ){
        h = 12
        dn = "AM"
    } else if ( h == 12 ) {
        dn = "PM"
    } else if ( h > 12 ) {
        h = h - 12
        dn = "PM"
    } else {
        dn = "AM"
    }

    return h.toString() + ":" + m.toString() + " " + dn.toString()
}

println(_24to12(time))

答案 1 :(得分:1)

Kevin的答案是正确的,应该会打勾...我只发布了它,因为它稍短了

{{1}}