Android时间下午0:00应该显示在12:00 pm

时间:2012-12-15 13:23:24

标签: java android date time

  

可能重复:
  Android date/time displaying 0 instead of 12

以下是我使用的代码:

public void onTimeSet( TimePicker view, int selectedHour,
            int selectedMinute ) {
        // Gets current time
        Calendar c = Calendar.getInstance();

        hour = selectedHour;
        minute = selectedMinute;

        // set waking time into textview
        StringBuilder sb = new StringBuilder();
        if( hour >= 12 ){                      
          sb.append(hour-12).append( ":" ).append(pad(minute)).append(" PM");
        }else if( hour == 0 ){
            sb.append( "12" ).append( ":" ).append( pad(minute) ).append( " AM" );
        } else if( hour == 24 ){
            sb.append(hour+24).append( ":" ).append( pad(minute) ).append( " PM" );
        }

        else{
          sb.append(hour).append( ":" ).append(pad(minute)).append(" AM");
        }

        // Assign hour set in the picker
        c.set( Calendar.HOUR, selectedHour );
        c.set( Calendar.MINUTE, selectedMinute );

        // Have Calendar calculate the substraction of hours and minutes
        c.add( Calendar.HOUR, SUB_HOUR );
        c.add( Calendar.MINUTE, SUB_MINUTE );

        // Get the hour and the minute calculated
        hour = c.get( Calendar.HOUR );
        minute = c.get( Calendar.MINUTE );
        //hour = c.get( Calendar.HOUR_OF_DAY );

        StringBuilder sb2 = new StringBuilder();
        if(hour>=12){                      
          sb2.append(hour-12).append( ":" ).append(pad(minute)).append(" PM");
        }else if(hour == 0){
          sb2.append( "12" ).append( ":" ).append(pad(minute)).append( " AM" );
        }
        else{
          sb2.append(hour).append( ":" ).append(pad(minute)).append(" AM");
        }

        // set current time into textview
        answer.setText( "To wake up at " + sb + ", you must go to bed at " + sb2 );

在我的第一个 StringBuilder 中,当用户选择中午12:00时,它显示在0:00 Pm而不是中午12:00,我该怎么办?提前谢谢。

1 个答案:

答案 0 :(得分:1)

建议的副本并没有真正回答这个问题。在构建字符串之前,您需要以下

hour = hour % 12
if(hour == 0)
    hour = 12;

__

更新: 在模数之前,执行以下操作:

// set this variable so it will be in scope

boolean morning = true
//then
if (hour >=12 && hour <  24) morning = false;
else morning = true; 

在stringbuilder中使用该布尔值