How to take Time Input in a line in Java?

621 Views Asked by At

The problem is for Java

I want to take time input as follows

12:00 AM 11:42 PM

There will be a sequence of such inputs up to N lines.

Here two different Time Inputs are given

1)12:00 AM

2)11:42 PM

but they are in the same line.

The time inputs are for a single person entering(12:00 AM) and leaving(11:42 PM)

I know SimpleDateFormat but I can't modify it to suit my needs as said.

So please help

5

There are 5 best solutions below

0
On

java.time and a regular expression

I recommend that you use java.time, the modern Java date and time API, for your time work. There are different ways to split the string into two to separate the two times in it; I too go for a regular expression. String.split() accepts one.

    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
    
    String inputLine = "12:00 AM 11:42 PM";
    String[] timeStrings = inputLine.split("(?<=M) ");
    if (timeStrings.length == 2) {
        LocalTime entering = LocalTime.parse(timeStrings[0], timeFormatter);
        LocalTime leaving = LocalTime.parse(timeStrings[1], timeFormatter);
        System.out.format("Entered %s, left %s.%n", entering, leaving);
    } else {
        System.err.println("Improper format: " + inputLine);
    }

Output from this snippet is:

Entered 00:00, left 23:42.

The regular expression (?<=M) matches a space preceded by an upper case M, so this is where the input string is being split.

Link: Oracle tutorial: Date Time explaining how to use java.time.

0
On

There is lots of ways of doing this. I would use Regular Expression.

        String input = "12:00 AM 11:42 PM";
        String pattern = "(\\d+:\\d+ AM) (\\d+:\\d+ PM)";

        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(input);

        if(m.find()) {
            String am = m.group(1);
            String pm = m.group(2);

        }

This gives you two strings am and pm.

Then you can use SimpleDateFormat to parse them as Date.

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm aa");
1
On

The format you are looking for is: hh:mm a.

From JavaDoc:

Symbol Desc Type Example
h clock-hour-of-am-pm (1-12) number 12
m minute-of-hour number 30
a am-pm-of-day text PM
1
On

This for the above problem , regular expression is very helpful to find and collect the value from input string/text. as given below.

public static void main(String[] args) {
        String input = "12:00 AM 11:42 PM";
        ArrayList<String> list = new ArrayList();
        Pattern pattern = Pattern.compile("[\\d:]*[ ](AM|PM)");
          //Matching the compiled pattern in the String
          Matcher matcher = pattern.matcher(input);
          while (matcher.find()) {
             list.add(matcher.group());
          }
          Iterator<String> it = list.iterator();
          System.out.println("List of matches: ");
          while(it.hasNext()){
             System.out.println(it.next());
          }
    }

here we have input string contains time. then we are using regex to find the pattern one the match found we are collecting that into list.

0
On

As everyone said, regex is the best option. I will provide you with a simple method. I will use BufferedReader as an example here. Feel free to use any input stream.

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

For n inputs simply accept n and start a loop.

int n = Integer.parseInt(bufferedReader.readLine().trim());
for (int i = 0;i < n;i++)

Each time you will accept each line of input consisting both date of arrival and departure as a single expression and split it using regex into 6 parts using delimiters : and whitespace. Eg: 12:00 AM 11:42 PM will be split into and array of Strings consisting of elements [12, 00, AM, 11, 42, PM].

String[] in = bufferedReader.readLine().split("[: ]");

//Array L to store HH MM XX of date of arrival at respective index
String[] L = new String[3];
L[0] = in[0];
L[1] = in[1];
L[2] = in[2];

//Array R to store HH MM XX of date of departure at respective index
String[] R = new String[3];
R[0] = in[3];
R[1] = in[4];
R[2] = in[5];

This approach will help you if want to perform any further calculations. You can also cast them to Integer using Integer wrapper class which will ease you in any type of arithmetic or comparative calculation. It is simple and straightforward, though a bit long.

I hope I have helped you.