【问题标题】:How do I get the time an hour from now for my 12 hour time format in string?如何从现在开始以字符串形式获取 12 小时时间格式的时间?
【发布时间】:2019-05-03 02:01:51
【问题描述】:

我打算在当前时间上增加一个小时,我已将其转换为 12 小时格式。只是不知道该怎么做。我想保持分钟不变,只是想增加一个小时,说时间是上午 11:59 -> 我想显示 12:59 下午,或者如果时间是 5:20,我想显示 6:20等等。 到目前为止,这是我的代码:

if (mDate.get(Calendar.AM_PM) == Calendar.AM)
            am_pm = "AM";
        else if (mDate.get(Calendar.AM_PM) == Calendar.PM)
            am_pm = "PM";


        String strHrsToShow = (mDate.get(Calendar.HOUR) == 0) ? "12" : mDate.get(Calendar.HOUR) + "";
        String strMinsToShow = (mDate.get(Calendar.MINUTE)) < 10 ? "0" + mDate.get(Calendar.MINUTE) : "" + mDate.get(Calendar.MINUTE);

        mRegisterGuestStartTime.setText(String.format("%s:%s %s", strHrsToShow, strMinsToShow, am_pm));

任何想法如何去做?提前致谢!

【问题讨论】:

    标签: android android-calendar android-timepicker android-date


    【解决方案1】:

    mDate 是我假设的Calendar 对象。如果是,为什么不使用Calendar.add(Calendar.HOUR, 1)?以字符串操作方式进行操作会丢失日期/时间值的精度。之后可以使用SimpleDateFormat 格式化日历

        // add an hour to the date
        mDate.add(Calendar.HOUR, 1);
    
        // prepare datetime formatter, sample output: "11:35 AM"
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm a");
        mRegisterGuestStartTime.setText(timeFormat.format(mDate.getTime()));
    

    【讨论】:

    • 您能否举例说明或更改我的代码以更新该场景
    • 更新了答案。 SimpleDateFormat 帮助您轻松打印所需的日期格式。有了它,您可以摆脱 if 语句来获取 AM/PM 或 24 小时汇总问题。更多信息请参考docs.oracle.com/javase/7/docs/api/java/text/…
    • 感谢 Brickowski 先生。我实际上需要: SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a",Locale.US);成功了。感谢您朝着正确方向迈出的一步!
    猜你喜欢
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 2013-04-16
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    相关资源
    最近更新 更多