在android中显示TimePicker中的当前时间

时间:2014-11-10 09:43:07

标签: android time picker

我使用此代码显示TimePicker中的当前时间,但我真的不知道,为什么它没有正确显示!?例如现在时间(系统时间)是下午2:56,但它显示凌晨2:56!我怎么解决呢?感谢。

 private long timer1 = 0; 
 ...

switch (view.getId()) {
        case R.id.add1: {
            if (timer1 == 0) {
                timer1 = getCurrentTime();
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(timer1);

            TimePicker timePicker = (TimePicker) findViewById(R.id.tp_1);
            timePicker.setCurrentHour(calendar.get(Calendar.HOUR));
            timePicker.setCurrentMinute(calendar.get(Calendar.MINUTE));



            break;
         . ..              
        }

private long getCurrentTime() {
    Calendar calendar = GregorianCalendar.getInstance();
    return calendar.getTimeInMillis();
}

当我想用下面的方法将此时间转换为String形式时,我也有同样的问题:

private String convertTimeToString(long time) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(time);

    int hour = calendar.get(Calendar.HOUR_OF_DAY);
    //int hour = get;
    int minute = calendar.get(Calendar.MINUTE);

    String timeSet;
    if (hour > 12) {
        hour -= 12;
        timeSet = "PM";
    } else if (hour == 0) {
        hour += 12;
        timeSet = "AM";
    } else if (hour == 12) {
        timeSet = "PM";
    } else {
        timeSet = "AM";
    }

    String minutes;
    if (minute < 10) {
        minutes = "0" + minute;
    } else {
        minutes = String.valueOf(minute);
    }
    // Append in a StringBuilder
    return String.format("%s:%s %s", hour, minutes, timeSet);

}

请帮助我!

3 个答案:

答案 0 :(得分:4)

<强>更新
1)错误的小时问题:尝试编辑这样的代码:

...
timePicker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY));
...

2)字符串表示问题:将日期/时间转换为字符串的一般方法如下:

String format = "hh:mm"; // or any other format - see note below
SimpleDateFormat formatter = new SimpleDateFormat(format);
formatter.format(yourDate);

或当您使用long时间戳时,最后一行将是:

formatter.format(new Date(yourLongTimestamp));

有用的链接
您可能会看到不同的日期/时间格式符号 here
测试您可能 here 的不同格式模式。

答案 1 :(得分:2)

// display current time
    public void setCurrentTimeOnView() {

        tvDisplayTime = (TextView) findViewById(R.id.tvTime);
        timePicker1 = (TimePicker) findViewById(R.id.timePicker1);

        final Calendar c = Calendar.getInstance();
        hour = c.get(Calendar.HOUR_OF_DAY);
        minute = c.get(Calendar.MINUTE);

        // set current time into textview
        tvDisplayTime.setText(
                    new StringBuilder().append(pad(hour))
                                       .append(":").append(pad(minute)));

        // set current time into timepicker
        timePicker1.setCurrentHour(hour);
        timePicker1.setCurrentMinute(minute);

    }

答案 2 :(得分:2)

替换此行:

timePicker.setCurrentHour(calendar.get(Calendar.HOUR));

要:

hourStart = c.get(Calendar.HOUR_OF_DAY);