android - 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
解决方案
您可以使用来自(而不是来自)的 ICU MessageFormat。格式字符串的语法在http://userguide.icu-project.org/formatparse/messages中描述android.icu.text.MessageFormat
java.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"
推荐阅读
- excel - 刷新 PowerPivot 时优雅地处理错误
- sharepoint - 使用 Microsoft Graph 从 SharePoint 检索自定义文档元数据
- telegram - 在 Telegram 消息标题中添加“通过 %Botname%”
- java - 将数组转换为列表
- materialize - 物化:视差不适用于移动设备
- python - 在 Python 中,我的 .split() 行中有一个值错误,返回 1 预期 2。添加空格没有帮助。data.txt 有问题吗?
- javascript - 根据条件从数组中获取一组值
- reactjs - 如何在开发模式下启动 React/Redux 应用程序?
- reactjs - paypal-checkout 沙盒卡在 heroku 上被拒绝,但在 localhost 上被接受
- javascript - 数组索引中的字符串 - Javascript