-1

So just as the title states my code is just throwing out the minutes part of any input time. Can't find any common questions so I'm making one. Code below

import java.util.Scanner;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class NewMain {
    public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
 System.out.print("\nDeparture time (HH:MM): ");
        String timeText = scanner.next();
           LocalTime time= LocalTime.parse(timeText, DateTimeFormatter.ofPattern("HH:MM"));
           System.out.print(time);
    }

}

If anyone can tell me what I'm doing wrong it would be grateful.

Nick
  • 11
  • 1
  • At a quick guess MM might be for month, try "mm" instead. Read the docs to be sure. – markspace Apr 12 '18 at 06:20
  • Your very first port of call should ALWAYS be the [JavaDocs](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html), a few second of reading will tell that `M/L month-of-year number/text 7; 07; Jul; July; J` and what you probably want is `m minute-of-hour number 30` ... – MadProgrammer Apr 12 '18 at 06:24
  • Possible duplicate [Java string to date conversion](https://stackoverflow.com/questions/4216745/java-string-to-date-conversion/4216767#4216767) – MadProgrammer Apr 12 '18 at 06:30

2 Answers2

1

You need to pass mm instead of MM

LocalTime time= LocalTime.parse(timeText, DateTimeFormatter.ofPattern("HH:mm"));

The complete formatting style for DateTimeFormatter is as below.

DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSX");

MM - Month

mm - Minutes

sameera sy
  • 1,708
  • 13
  • 19
0

Provide input as 11:30 04:30 if provide 4:30 then it will throw error while parsing

import java.util.Scanner;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class dateTime {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("\nDeparture time (HH:MM): ");
    String timeText = scanner.next();
       LocalTime time= LocalTime.parse(timeText, 
DateTimeFormatter.ofPattern("HH:mm"));
       System.out.print(time);
}

}
Rohan Shukla
  • 533
  • 1
  • 4
  • 16