#How to throw error if string does not contain a date

1 messages · Page 1 of 1 (latest)

left walrus
#

Basically, i'm taking input where user inputs a message seperated by |, e.g message xyz | 20/4/24 20:23, but we can accept any form of date, it can be just a day, or the time can be just 20 but i want to make sure it's there

south phoenixBOT
#

<@&987246399047479336> please have a look, thanks.

#

Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#
TJ-Bot
Basically, i'm taking input where user inputs a message seperated by |, e.g `message xyz | 20/4/24 20:23`, but we can accept any form of date, it can be just a day, or the time can be just `20` but i want to make sure it's there

an be in different formats like MM/dd/yyyy or dd-MM-yyyy HH:mm. To validate if the input string contains a date, you can use the SimpleDateFormat class in Java.

Here's a simple code snippet to check if a string contains a date:

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class Main {
    public static void main(String[] args) {
        String input = "message xyz | 20/4/24 20:23";
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm");
        
        try {
            dateFormat.parse(input);
            System.out.println("Input contains a valid date");
        } catch (ParseException e) {
            System.out.println("Error: Input does not contain a valid date");
            // throw new IllegalArgumentException("Error: Input does not contain a valid date");
        }
    }
}

You can uncomment the throw new IllegalArgumentException() line if you want to throw an error instead of just printing a message. This way, you can handle cases where the input string does not contain a valid date format.

dense shard
#

U can use date type

#

But if u need string

#

There is smth like regex

#

And with it u can check

#

U need to search regex what u want

#

To valid date

stuck finch
#

You'd need to parse it, be it through a formatter/regex check/... and then throw an exception.

sacred marsh
#

I think he just wants to test if any text follows, regardless of it's conformance to a known date type.