Reputation: 11
I need to write a program that will verify whether a given date if valid or invalid. The date is in the mm/dd/yyyy format and i need to figure out a way to split the string into months, days, and years to determine if the date is valid or not. I can't just have the month day and year input separately either, so this is causing a problem. Basically I just need to figure out how to split up the string for the various months so i can work with each month's number of days and use that to verify the date. Any help you could give me would really be appreciated I'm stuck on this and cant figure it out. Thanks.
Upvotes: 1
Views: 76
Reputation: 2845
Try with SimpleDateFormat
Date date = null;
try {
String target = "07/30/1991";
DateFormat df = new SimpleDateFormat("M/d/yyyy", Locale.ENGLISH);
date = df.parse(target);
} catch (ParseException ex) {
date = null;
}
if (date != null) {
// Or you use the deprecated methods .. just saying
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
}
Upvotes: 0
Reputation: 21608
It's nearly never a good idea to parse a date on your own. Dates are mysterious things: leap seconds, leap years, time zones, etc. are a ultra complex thing.
To check a date I would really recommend to use the java functions for that task (or a library). Here is an example:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Snippet {
public static void main(String[] args) throws ParseException {
// define your own date format
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
// for strict parsing of dates, turn of lenient mode
dateFormat.setLenient(false);
// try to parse the date
Date date = dateFormat.parse("13/31/1604");
// if no exception occurs, your date is a valid date
System.out.println("date valid");
}
}
Upvotes: 1
Reputation:
You should use DateFormat
like other suggested. If that is not an option, I guess you can do this:
String myDate = "10/23/1991";
String[] split = myDate.split('/');
String month = split[0];
String day = split[1];
String year = split[2];
Upvotes: 2