Check that an input is a Date Java [duplicate] - java

This question already has answers here:
Java: Check the date format of current string is according to required format or not [duplicate]
(8 answers)
Closed 7 years ago.
Hi is there a way to check if an input is a date in Java, the date format is DD/MM/YYYY so int\int\int
I have the basic check if (x != "") but I was wondering if you check that it is a date.
Now I'me getting a new error code:
try {
date = (Date) dateFormat.parse(dateInput);
} catch (ParseException e1) {
System.out.println("FAIL!!!!!!!!");
JOptionPane.showMessageDialog(null, "Date entered is incorrect, please close this window and try again");
new BookApp();
}
The indents probably got messed in when I copied and pasted it, but when the format is wrong it works and the dialog menu pops up. But when I give 12\08\2015 it give a ClassCastError.
How do I get this working?

1) Create a formatter for your date pattern :
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
2) Try to format your String input to a date :
Date date = dateFormat.parse(input);
Now, if the input doesn't match your pattern, you get a ParseException.

You can always try to parse the date and capture if the parse was successful or not.
The SimpleDateFormat will throw an exception if the string was not parsable as a date.
public boolean isDate(String dateString) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
return dateFormat.parse(dateString) != null;
} catch (ParseException e) {
return false;
}
}

Related

Convert String month to Int month [Java] [duplicate]

This question already has answers here:
Change date format in a Java string
(22 answers)
Closed 5 years ago.
I'm trying to convert a String month to a int month in Java. I do not want my program to have a lot of logic on it, so I'm trying to do it without having to create a switch case or a Enum. If not possible, i'll have to do deal with it and create that logic...
My String Sample is this:
String date = "2017-Oct-27";
And I want it to be like this:
String date = "2017-10-27";
Can anyone help me please?
Thanks
Please try below code
String input = "2017-Oct-27";
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MMM-dd");
String formattedDate= "";
Date date;
try {
date = parser.parse(input);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
formattedDate = formatter.format(date);
} catch (ParseException e1) {
e1.printStackTrace();
}

How can I check if my Date is correct? [duplicate]

This question already has answers here:
How to sanity check a date in Java
(24 answers)
Closed 5 years ago.
I'm programming a window where the user has to type a date on a input field but I don't know how to check if the day or month are coherent or not (like day between 1-31 and month between 1-12)
String string = "26/03/2017";
DateFormat format = new SimpleDateFormat("dd/MM/yyyy") ;
try {
Date date = format.parse(string);
} catch (ParseException e) {
e.printStackTrace();
}
This is the piece of code where I'm formatting the Date, but I have no idea to check what I said before.
Trying to parse a string like this: string = "36/03/2017"; can return a totally legal date object but an incorrect value respect the string.
for that case you can use the lenient flag of the class SimpleDateFormat, setting that flag to false will throw an exception for invalid strings representations of a date (e.g. 29 Feb 2017)
now, you can set the flag Lenient to false, and catch the exception
String string = "36/03/2017";
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
format.setLenient(false);
try {
Date date = format.parse(string);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
DateFormat has a property which named 'lenient' is default true.
You must set format.setLenient(false) to check validity of the date. if incorrect date is parsed, you get a ParseException.
2017 answer.
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/uuuu")
.withResolverStyle(ResolverStyle.STRICT);
try {
LocalDate.parse(string, format);
} catch (DateTimeParseException e) {
System.out.println("Not a valid date: " + string);
}
While SimpleDateFormat has two degrees of strictness, lenient and non-lenient, DateTimeFormatter has three, strict, smart and lenient. For validation I recommend strict. Smart is the default, so we need to set it explicitly.
There are many more details in this answer.
I suggest to use regex. For your date format it should be something like:
(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d
You can also find more patterns and validate them here: http://html5pattern.com/Dates

Java convert Date in string to Date [duplicate]

This question already has answers here:
Java string to date conversion
(17 answers)
Closed 6 years ago.
how to convert this string "2016-10-08T01:00:00-07:00" to date object in Java?
I want to know what is string format to use with SimpleDateFormat.
I have try
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
try {
Date date = format.parse("2016-10-08T01:00:00-07:00");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Change your format from Z to X will work . Detail is here
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Date date = format.parse("2016-10-08T01:00:00-07:00");
should be
Date date = format.parse("2016-10-08T01:00:00-0700");
The time zone should not have a colon delimiting hours and minutes.
You can try SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
Best solution to refer # Change date format in a Java string

Parse string to Date Java [duplicate]

This question already has an answer here:
Android Studio unhandled exception warnings
(1 answer)
Closed 6 years ago.
I have a database that saves a date in string.
Before saving it to my db, I put the date in format yyyy-MM-dd HH:mm with SimpleDateFormat.
I manage to fetch the String from my db and the format is correct.
My problem is when I try to set my Calendar with the setTime() function I require a Date. So basically I need to convert the String sent by my database into the Date format. When I try to do so I get ParseException error
Here is an example:
private Calendar c;
private SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm");
private String myDate;
private Date d;
myDate = db.getDate() //This works I output correct date
d = dateFormat.parse(date); // Error Message : Unhandled Exception: java.text.ParseException
c.setTime(d); //Needs Date Format to set time
It's not an error, IDE (Android Studio) is asking you to handle the exception to prevent run time exception. Include that in try catch block:
try {
d = dateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}

Reading input matching exact date pattern YYYY-MM-DD [duplicate]

This question already has answers here:
Parse String date in (yyyy-MM-dd) format
(5 answers)
Closed 7 years ago.
I have a Java application that reads information about a new user to insert into an SQL database. When the user is to input a new user's date of birth, I want to program to be sure that the user has entered a date that is in the exact format YYYY-MM-DD.
I want to use the Scanner method next(Pattern pattern), but I'm not sure exactly how to create the necessary Pattern for what I'm trying to achieve. Here is what I have so far:
String date [] = null;
while (date == null) {
try {
date = userInput.next(Pattern.compile(*your suggestion here*)).split("-");
} catch (NoSuchElementException e) {
System.out.print("Date must be in format YYYY-MM-DD: ");
date = null;
userInput.nextLine();
continue;
}
}
What should I put in *your suggestion here*?
Use SimpleDateFormat as a date parser, not a regex.

Categories

Resources