【问题标题】:Is there a way to force a single digit Int into a two digit int value?有没有办法将一位数 Int 强制转换为两位数 int 值?
【发布时间】:2018-07-28 22:04:08
【问题描述】:

我需要在我的应用中显示时间。我以整数形式将小时和分钟值存储到数据库中。一切正常,但我不喜欢当值下降到一位数时,因为它看起来像一个 4 值时钟。我的意思是,如果时间为 6 小时 3 分钟,则输出“6:3”,如果时间为 11 小时 11 分钟,则输出“11:11”。无论值如何,我都希望它始终显示 4 个数字。

发生了什么:

早上 6:3(6 小时 3 分钟)

上午 11:11(11 小时 11 分钟)

我想要什么

上午 6:03(6 小时 3 分钟)

下午 4:08(4 小时 8 分钟)

上午 11:11(11 小时 11 分钟)

谢谢。

【问题讨论】:

  • 你为什么不使用 System.currentTimeMillis() 方法在你的数据库中节省时间,然后在日期/日历库的帮助下将它转换为你想要的任何形式??

标签: android integer int digit


【解决方案1】:

你要找的是String formatting

例如,String.format("%02d", minutes)minutes 格式化为 2 位整数,必要时用零填充。

【讨论】:

    【解决方案2】:
    private String getMinutesInTwoDigits(String time) {
        SimpleDateFormat dateFormatGiven = new SimpleDateFormat("h:m a");
        SimpleDateFormat dateFormatRequired = new SimpleDateFormat("h:mm a");
        String result = null;
        try {
            result = dateFormatRequired.format(dateFormatGiven.parse(time));
        } catch (ParseException e) {
            return time;
        }
        return result;
    }
    

    【讨论】:

    • 谢谢你,但我可以看到你认为给定的日期格式为 h:m 但也可能是 hh:mm...@JunaidKhan
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多