Android date/time displaying 0 instead of 12

2019-02-16 05:29发布

I wonder what's wrong with my code below:

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

        // For alternative times
        c.add( Calendar.HOUR, SUB_SIX_HOUR );
        c.add( Calendar.MINUTE, SUB_FLAT_MINUTE );

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

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


        alternative.setText( "Alternative times: " + sb3 + " (9 hours)" + sb4 + " (6 hours)" );

Please help me figure out how to display 12 instead of 0 when the calculated time is 12:00 midnight. Thanks!

2条回答
我只想做你的唯一
2楼-- · 2019-02-16 05:51
 hour = c.get( Calendar.HOUR );
 minute = c.get( Calendar.MINUTE );
 hour = c.get( Calendar.HOUR_OF_DAY );

You are setting hour again after it was already set.

查看更多
够拽才男人
3楼-- · 2019-02-16 05:52

Use this to check for AM or PM.

c.get(Calendar.AM_PM);

See here for documentation Calendar.AM_PM

查看更多
登录 后发表回答