需要将时间转换为hh:mm

时间:2015-03-18 19:52:33

标签: java

我正在用Java做一个时间转换程序,我需要修复代码。当我尝试显示3:04时,它将显示3:4。我需要修复在少于10的数字前面显示零,没有if语句,只导入java.util.Scannerjava.text.NumberFormat。它必须在一个班级。我想在今晚完成。如果有人可以提供帮助,我会很感激。这是下面的代码。我已经导入了上面提到的这两个java类。

    Scanner sc = new Scanner(System.in);


    final int MINUTES_IN_HOUR = 60;
    int Minutes, Hours, InputedMinutes; 

    System.out.println("Enter a number in minutes: ");
    InputedMinutes = sc.nextInt();
    sc.close();

    Hours = InputedMinutes/MINUTES_IN_HOUR;
    Minutes = InputedMinutes%MINUTES_IN_HOUR;

    System.out.println("Your time is " + Hours + ":" + Minutes);    
}

2 个答案:

答案 0 :(得分:3)

使用format

System.out.format("%d:%02d", Hours, Minutes);

有关格式规范,请参阅Java documentation

答案 1 :(得分:1)

您也可以使用printf并使用日期时间格式器,如下所示

Date date = new Date(); // For Date objects from java.util.date

System.out.printf("Clock time is = %1$tH:%1$tM", date); // Prints hour and minute of the local clock time.

但是您正在使用以下方式显示数字格式:

System.out.printf("%d:%02d", Hours, Minutes);

或使用格式化方法:

System.out.format("%d:%02d", Hours, Minutes);

<强>更新

由于您上次关于使用NumberFormat(或具体类)的评论,以下内容也适用于您的情况(请参阅IDEONE中的操作):

int hours = 30;
int minutes = 3; // or could be 30;

/* 
 * Shows two digits and replaces with 0 if absent (if you use 0)
 *
 * If you use # instead of 0, it will NOT SHOW the leading 0
 *
 */

DecimalFormat df = new DecimalFormat("00"); 

String formattedHours = df.format(hours);
String formattedMinutes = df.format(minutes);

System.out.printf("Clock hours and minutes = %s:%s", formattedHours, formattedMinutes);

有关详细信息,请参阅Oracle的Customizing Formats

相关问题