如何在整数值前添加零

时间:2018-01-20 06:06:40

标签: java time number-formatting leading-zero

我正在尝试计算用户输入以空格分隔的小时和分钟的未来时间。 当用户输入计算未来分钟数小于10的分钟时,我就会坚持下去。

例如,如果当前时间是10:04而用户输入1小时4分钟,则未来时间应该是11:08。

相反,我打印11:8

int extraHours = minutesGiven/60;
hoursGiven = hoursGiven+extraHours;
// System.out.println("hoursGiven= " + hoursGiven);
int extraMinutes = minutesGiven%60;

if((minutesNow + extraMinutes)>59){
    minutesNow = minutesNow + extraMinutes-60;
}else if((minutesNow+hoursGiven)<10){
    minutesNow = minutesNow + extraMinutes;
    String padded = String.format("%02d" , minutesNow);
}else{
    minutesNow = minutesNow + extraMinutes;
}

//calculate the future hour
int futureHours = 0;
if(minutesGiven==30){
    futureHours = (hourNow + hoursGiven +1)%24;
}else{
    futureHours = (hourNow + hoursGiven)%24;
}
//print the time
System.out.println("The time will be " + futureHours + ":" + minutesNow);

// LocalTime noon = LocalTime.of(12, 0); //12 hours, 0 minutes
//System.out.println("Noon printed as a LocalTime object: " + noon);

4 个答案:

答案 0 :(得分:2)

打印时间时创建一个if语句:

if (minutesNow < 10)
    System.out.println("The time will be " + futureHours + ":0" + minutesNow);
else
    System.out.println("The time will be " + futureHours + ":" + minutesNow);

希望它有所帮助;)

答案 1 :(得分:1)

您可以使用java8的LocalTime类。

Scanner s = new Scanner(System.in);
System.out.print("Enter hour and minute: ");
int hour = s.nextInt();
int minute = s.nextInt();

LocalTime time = LocalTime.now();
time = time.plusHours(hour).plusMinutes(minute);

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm");
System.out.println("\n" + "\n" + formatter.format(time));
s.close();

答案 2 :(得分:0)

您可以将0添加到像这样的整数

String time = String.ValueOf(hours) +":"+ "0"+String.ValueOf(minutes);

答案 3 :(得分:0)

您可以使用DateCalendar个对象来实现此目的。它们会自动为您提供填充,并尊重任何可能的夏令时调整:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

class Main {    
    public static void main(String[] args) {
        int minutesNow = 4;
        int hourNow = 10;
        int minutesGiven = 4;
        int hoursGiven = 1;
        try {
            String myTime = hourNow + ":" + minutesNow;
            SimpleDateFormat df = new SimpleDateFormat("HH:mm");
            Date d = df.parse(myTime);
            Calendar cal = Calendar.getInstance();
            cal.setTime(d);
            cal.add(Calendar.MINUTE, minutesGiven);
            cal.add(Calendar.HOUR, hoursGiven);
            String newTime = df.format(cal.getTime());
            System.out.println("The time will be " + newTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}