2

我收到一条以秒为单位的文本(例如 7261)。我需要将它转换成这种格式:2h, 1m, 1s

我正在使用 time4j 库。根据他们的Github page,我正在做这样的事情:

val duration = Duration.of(7261, ClockUnit.SECONDS).with(Duration.STD_CLOCK_PERIOD)
val prettifiedDuration = PrettyTime.of(Locale.ENGLISH).print(duration)

但是,我收到此错误:

06-22 11:50:52.133 12161 12244 E AndroidRuntime: java.lang.ExceptionInInitializerError
06-22 11:50:52.133 12161 12244 E AndroidRuntime:    at net.time4j.base.ResourceLoader.getInstance(ResourceLoader.java:167)
06-22 11:50:52.133 12161 12244 E AndroidRuntime:    at net.time4j.PrettyTime.<clinit>(PrettyTime.java:95)
06-22 11:50:52.133 12161 12244 E AndroidRuntime:    at net.time4j.PrettyTime.of(PrettyTime.java:198)

任何想法?甚至,更好的解决方案?

4

2 回答 2

3

所以,我意识到 Android 项目有一个单独的库: https ://github.com/MenoData/Time4A

对于 Gradle,添加此依赖项:

implementation("net.time4j:time4j-android:4.6-2020a")

在您的 Application 类中,初始化库:

class MyApplication : DaggerApplication() {

    override fun onCreate() {
        super.onCreate()
        ApplicationStarter.initialize(this, true)
    }
}

然后你可以按照问题中的描述使用它。

于 2020-06-22T13:13:03.000 回答
0

您是否缺少一些依赖项?

    <dependency>
        <groupId>net.time4j</groupId>
        <artifactId>time4j-base</artifactId>
        <version>5.6</version>
    </dependency>
    <dependency>
        <groupId>net.time4j</groupId>
        <artifactId>time4j-sqlxml</artifactId>
        <version>5.6</version>
    </dependency>
    <dependency>
        <groupId>net.time4j</groupId>
        <artifactId>time4j-tzdata</artifactId>
        <version>5.0-2020a</version>
    </dependency>

在我的测试中,您的代码运行良好。

val duration = Duration.of(7261, ClockUnit.SECONDS).with(Duration.STD_CLOCK_PERIOD)
val prettifiedDuration = PrettyTime.of(Locale.ENGLISH).print(duration)

println(prettifiedDuration)

输出:

2 hours, 1 minute, and 1 second
于 2020-06-22T11:09:29.780 回答