CCL
CCL

Reputation: 15

Getting 2 seperate time values using regex in Java

So far I have successfully got the time values from a text file. '09:00 19:00'. This is what the time values are set out like in the text file. Is there any way to get it so these 2 values are seperate. Like "Start time - 09:00" and "End time - 19:00". I have been able to get the values '09:00 19:00' from the text file. It is just the ability to seperate them that I cannot find

String available = null;
        Boolean isAvail;
        Date day = new Date();

        SimpleDateFormat simpleDateformat = new SimpleDateFormat("EEEE");
        String token1 = "";

        Scanner inFile1 = new Scanner(new File("D:\\Jordanstown\\NetBeans Projects\\COM373\\Availabilty Update File.txt")).useDelimiter(",\\s*");

        List<String> availability = new ArrayList<String>();

        while (inFile1.hasNext()) 
            {
                token1 = inFile1.next();
                availability.add(token1);
                }
        inFile1.close();


    String[] availabilityArray = availability.toArray(new String[0]);

    String searchArray = simpleDateformat.format(day);
    for (String curVal : availabilityArray)
    {
        if (curVal.contains(searchArray))
        {
        Pattern pattern = Pattern.compile("'(.*?)'");
        Matcher matcher = pattern.matcher(curVal);
            if (matcher.find())
            {
                //System.out.println(matcher.group(1));
                available = matcher.group(1);

            }
        }
    }
    //I would want to have these 2 strings being the 2 times from the text file
    String timeStart = "14:00";
    String timeEnd = "20:00";

    LocalTime start = LocalTime.parse(timeStart);
    LocalTime stop = LocalTime.parse(timeEnd);
    LocalTime now = LocalTime.now();
    if (now.isAfter(start) && now.isBefore(stop)) 
    {
        isAvail = true;
        System.out.println(isAvail);
    }else{
        isAvail=false;
        System.out.println(isAvail);
    }

Thank you for any help in advance

Upvotes: 0

Views: 35

Answers (1)

Andreas
Andreas

Reputation: 159086

Simply split the string on the separating space.

String input = "09:00 19:00";
String[] values = input.split(" ");
String startTime = values[0];
String endTime = values[1];
System.out.println(startTime); // prints: 09:00
System.out.println(endTime);   // prints: 19:00

You can also use indexOf and substring:

String input = "09:00 19:00";
int idx = input.indexOf(' ');
String startTime = input.substring(0, idx);
String endTime = input.substring(idx + 1);
System.out.println(startTime); // prints: 09:00
System.out.println(endTime);   // prints: 19:00

These are all common methods on the String class, and you should have been able to find them yourself, if you just read the documentation, i.e. the javadoc of String.

Upvotes: 1

Related Questions