首页 > 解决方案 > Android默认方法可以正确获取1天1小时的日期和时间

问题描述

我已经编写了 if-else 条件来显示日期和时间,例如 1 天、1 小时等。我想知道是否有任何函数可以在不添加这些条件的情况下执行此操作。我在这里发布我的代码

if(days.toInt() == 0 && hours.toInt() > 1)
            {
                result = "$hours hours"
            }
            else if(hours.toInt() == 0 && days.toInt() > 1)
            {
                result = "$days days"
            }
            else if(days.toInt() == 1 && hours.toInt() > 1)
            {
                result = "$days day $hours hours"
            }
            else if(hours.toInt() == 1 && days.toInt() > 1)
            {
                result = "$days days $hours hour"
            }
            else if(days.toInt() == 1 && hours.toInt() == 0)
            {
                result = "$days day"
            }
            else if(days.toInt() == 0 && hours.toInt() == 1)
            {
                result = "$hours hour"
            }
            else if(days.toInt() == 1 && hours.toInt() == 1)
            {
                result = "$days day $hours hour"
            }
            else if(hours.toInt() == 0 && days.toInt() ==0)
            {
                result = ""
            }
            else if(hours.toInt() > 1 && days.toInt() > 1)
            {
                result = "$days days $hours hours"
            }
            return result

标签: androidkotlincalendarsimpledateformatdateformatter

解决方案


您可以使用来自(而不是来自)的 ICU MessageFormat。格式字符串的语法在http://userguide.icu-project.org/formatparse/messages中描述android.icu.text.MessageFormatjava.text

MessageFormat.format(
        "{days,plural,=1{# day} other {# days}}{hours,plural,=0{} =1{ # hour} other { # hours}}", mapOf<String, Any?>(
            "days" to 2,
            "hours" to 0
        ))

您可能还想查看RelativeDateTimeFormatter ,但它给出的英文字符串与您的示例略有不同。

 RelativeDateTimeFormatter fmt = RelativeDateTimeFormatter.getInstance();
 fmt.format(1, Direction.NEXT, RelativeUnit.DAYS); // "in 1 day"

推荐阅读