0

for example if the user input is 1.71 (1 hour and 71 minutes), then i want to convert it to 2.11 (2 hours and 11 minutes)

DecimalFormat time = new DecimalFormat("##.## p.m");

int userInput = 1.71;

System.out.print(time.format(userInput));
Filburt
  • 17,626
  • 12
  • 64
  • 115
Manuel Buenrostro
  • 121
  • 1
  • 2
  • 5
  • 1
    From where did you get that input? The user? Much better to store nd parse that input as a string imho. – aioobe Dec 16 '14 at 07:46
  • possible duplicate of [JAVA convert minutes into default time \[hh:mm:ss\]](http://stackoverflow.com/questions/27060759/java-convert-minutes-into-default-time-hhmmss) – MihaiC Dec 16 '14 at 08:33

3 Answers3

1

Parse the input as date and than format the date to your output format:

  Scanner sc = new Scanner(System.in);
  DateFormat df = new SimpleDateFormat("HH.mm");
  DateFormat dfout = new SimpleDateFormat("H.mm a");
  Date date  = df.parse(sc.next());
  System.out.println(dfout.format(date));
Jens
  • 67,715
  • 15
  • 98
  • 113
0

I'm not sure whether I get your question right, but shouldn't the following work?

int hours = (int)userInput;
decimal minutestmp = ((userInput - hours) * 60);
int minutes = (int)minutestmp;

String TimeString = hours + ":" + minutes;
Date date = new SimpleDateFormat("HH:mm").parse(TimeString);
String newTimeString = new SimpleDateFormat("H:mm").format(date);
Edi G.
  • 2,432
  • 7
  • 24
  • 33
0

ISO 8601

The ISO 8601 standard for date-time strings defines a format for what they call Durations: PnYnMnDTnHnMnS.

Joda-Time

The Joda-Time library knows how to parse and generate such strings.

So first, transform your input into such a string. Then feed that new string into Joda-Time. Lastly ask Joda-Time to recalculate the hours and minutes. All of this has been covered on StackOverflow multiple times. Please search for details.

To translate that input, replace the period, and prepend and append.

String d = "PT" + "1.71".replace( ".", "H") + "M";  // PT1H71M

Feed to Joda-Time.

Period period = Period.parse( d );

Normalize the minutes.

Period p = period.normalizedStandard();

Alternatively, you could tear apart the hours and minutes portions of your input, then feed them as ints to a constructor of Period.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154