I'd like to validate several date formats, as below examples :
YYYY
YYYY-MM
YYYY-MM-DD
Validation must ensure that date format is correct and the date exists.
I'm aware that Java 8 provides a new Date API, so I'm wondering if it's able to do such job.
Is there a better way using Java 8 date API ?
Is it still a good practice to use Calendar class with lenient parameter ?
You can specify missing fields with parseDefaulting to make all the formatters working:
public static boolean isValid(String input) {
DateTimeFormatter[] formatters = {
new DateTimeFormatterBuilder().appendPattern("yyyy")
.parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.toFormatter(),
new DateTimeFormatterBuilder().appendPattern("yyyy-MM")
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.toFormatter(),
new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd")
.parseStrict().toFormatter() };
for(DateTimeFormatter formatter : formatters) {
try {
LocalDate.parse(input, formatter);
return true;
} catch (DateTimeParseException e) {
}
}
return false;
}
Use optional fields and parseBest
You only want to validate, I understand that, but afterwards you'll most likely want to extract the data in an appopriate way. Fortunately, and indeed as you wrote, Java 8 provides such a method, parseBest.
parseBest works with optional fields. So define the format you want to parse first: yyyy[-MM[-dd]], with the brackets ([ and ]) wrapping the optional fields.
parseBest also requires you to provide several TemporalQuery<R>. Actually, it's just a functional wrapper around a template method <R> R queryFrom(TemporalAccessor). So we can actually define a TemporalQuery<R> as simply as Year::from. Good: that's exactly what we want. The thing is that parseBest is not really well named: it will parse all in order and stop after the first proper TemporalQuery that matches. So in your case, we have to go from most precise to less precise. Here are the various types that you want to handle: LocalDate, YearMonth and Year. So let's just define the TemporalQuery[] as LocalDate::from, YearMonth::from, Year::from. Now, if parseBest doesn't recognize your input, it will throw an exception.
All in all, we'll construct the parseBest as follow:
parseBest(DateTimeFormatter.ofPattern("yyyy[-MM[-dd]]"), LocalDate::from, YearMonth::from, Year::from);
So let's write it properly:
static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy[-MM[-dd]]");
static TemporalAccessor parseDate(String dateAsString) {
return FORMATTER.parseBest(dateAsString, LocalDate::from, YearMonth::from, Year::from);
}
But... you only want to validate... Well in that case, a date is computed and the expensive job is already done. So let's just define the validation as follow:
public static boolean isValidDate(String dateAsString) {
try {
parseDate(dateAsString);
return true;
} catch (DateTimeParseException e) {
return false;
}
}
I know, it's bad to use exceptions to handle cases like this, but while the current API is very powerful this very specific case wasn't taken in account so let's just stick to it and use it as is.
But now, we have this issue: invalid dates can be parsed. For instance "2018-15" will be parsed as Year{2018} because Year is the best TemporalAccessor that the parser can use: YearMonth would fail, but it is a YearMonth, so it must be valid according to that. So let's just pass it again in the FORMATTER.
public static boolean isValidDate(String dateAsString) {
try {
TemporalAccessor date = parseDate(dateAsString);
return FORMATTER.format(date).equals(dateAsString);
} catch (DateTimeParseException e) {
return false;
}
}
Here's the full code:
import java.time.*;
import java.time.format.*;
import java.time.temporal.*;
class Main {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy[-MM[-dd]]");
static TemporalAccessor parseDate(String dateAsString) {
return FORMATTER.parseBest(dateAsString, LocalDate::from, YearMonth::from, Year::from);
}
public static boolean isValidDate(String dateAsString) {
try {
TemporalAccessor parsedDate = parseDate(dateAsString);
return FORMATTER.format(parsedDate).equals(dateAsString);
} catch (DateTimeParseException e) {
return false;
}
}
public static void main(String[] args) {
String[] datesAsString = {
"2018",
"2018-05",
"2018-05-22",
"abc",
"2018-",
"2018-15",
};
for (String dateAsString: datesAsString) {
System.out.printf("%s: %s%n", dateAsString, isValidDate(dateAsString) ? "valid" : "invalid");
}
}
}
Try it online!
Output:
2018: valid
2018-05: valid
2018-05-22: valid
abc: invalid
2018-: invalid
2018-15: invalid
You want more than validating, like getting the actual value?
Note that you can still use the data retrieved from parseBest for further uses like this:
TemporalAccessor dateAccessor = parseDate(dateAsString);
if (dateAccessor instanceof Year) {
Year year = (Year)dateAccessor;
// Use year
} else if (dateAccessor instanceof YearMonth) {
YearMonth yearMonth = (YearMonth)dateAccessor;
// Use yearMonth
} else if (dateAccessor instanceof LocalDate) {
LocalDate localDate = (LocalDate)dateAccessor;
// Use localDate
}
But be careful because as mentioned earlier, "2018-15" will still be parsed, as Year{2018} and not YearMonth{2018,15}, or "2018-02-30" will still be parsed as a YearMonth and not as a LocalDate.
To validate the YYYY-MM-DD format, you can simply use LocalDate.parse introduced in java.time since JDK 8.
Obtains an instance of LocalDate from a text string such as
2007-12-03.
The string must represent a valid date and is parsed using
DateTimeFormatter.ISO_LOCAL_DATE.
A DateTimeParseException will be thrown if the date is invalid.
For the other two formats you gave us, the exception would be thrown. That is logical because they are not real date, simply part of a date.
LocalDate also provide a method of(int year, int month, int dayOfMonth) thus if you really want to validate simply the year in some case, the year with the month in other case or the full date then you could do something like this :
public static final boolean validateInputDate(final String isoDate)
{
String[] dateProperties = isoDate.split("-");
if(dateProperties != null)
{
int year = Integer.parseInt(dateProperties[0]);
// A valid month by default in the case it is not provided.
int month = dateProperties.length > 1 ? Integer.parseInt(dateProperties[1]) : 1;
// A valid day by default in the case it is not provided.
int day = dateProperties.length > 2 ? Integer.parseInt(dateProperties[2]) : 1;
try
{
LocalDate.of(year, month, day);
return true;
}
catch(DateTimeException e)
{
return false;
}
}
return false;
}
Note that you mentionned several formats but did not provide them, so I assumed these were the only 3.
public static final boolean validateInputDate(final String isoDate, final String dateFormat){
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
try {
final Date date = simpleDateFormat.parse(isoDate);
System.out.println("Date: " + date);
return true;
} catch (ParseException e) {
e.printStackTrace();
return false;
}
}
You can use lenient, is your default is true:
in SimpleDAteFormat
SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
sdf.setLenient(false);
or in JSON validate:
#JsonFormat(lenient = OptBoolean.FALSE)
Please use the below code. This will validate and also works in every format.
public class DateValidator {
public static void main(String[] args) {
String datetoCheck = "999999";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMdd");
try {
LocalDate localDate = LocalDate.parse(datetoCheck, formatter);
System.out.println(localDate);
} catch ( DateTimeException ex ) {
ex.printStackTrace();
}
}
}
Related
I need to validate Strings if they contain a valid Date-Input. For that I created a method
public static Date validateDateFormat(final String expectedDateFormat, final String dateToValdate) {
DateTimeFormatter formatter = DateTimeFormat.forPattern(expectedDateFormat);
DateTime dt = null;
try {
dt = formatter.parseDateTime(dateToValdate);
} catch (Exception e) {
log.error("cannot parse {0} to format {1}", dateToValdate, expectedDateFormat);
}
if (dt != null) {
return dt.toDate();
}
else {
return null;
}
}
With these values it does not return null as expected. The string will be converted to a DateTime with the value 0018-12-18T00:00:00.000+00:53:28, is there a way to change this behaviour? I though that if the format is not correct, it will fail.
Here my Test
#Test
public void checkFormat6() {
String date = "18.12.18";
String expectedFormat = "dd.MM.yyyy";
assertNull(DateFormatChecker.validateDateFormat(expectedFormat, date));
}
I need to use JDK 7 and using joda-time 2.10
Joda Time doesn't strictly match the y, yy, or yyyy. Even d.M.y pattern will parse 18.12.18 into a valid date time.
You can get a more strict pattern parsing with java.time classes (there is a backport for Java 7) e.g. by setting ResolverStyle.STRICT:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(expectedFormat)
.withResolverStyle(ResolverStyle.STRICT);
Above will fail dd.MM.yyyy from your example but it will still let d.M.y parse 18.12.18.
I find it curious that the most obvious way to create Date objects in Java has been deprecated and appears to have been "substituted" with a not so obvious to use lenient calendar.
How do you check that a date, given as a combination of day, month, and year, is a valid date?
For instance, 2008-02-31 (as in yyyy-mm-dd) would be an invalid date.
Key is df.setLenient(false);. This is more than enough for simple cases. If you are looking for a more robust (I doubt that) and/or alternate libraries like joda-time, then look at the answer by user "tardate"
final static String DATE_FORMAT = "dd-MM-yyyy";
public static boolean isDateValid(String date)
{
try {
DateFormat df = new SimpleDateFormat(DATE_FORMAT);
df.setLenient(false);
df.parse(date);
return true;
} catch (ParseException e) {
return false;
}
}
As shown by #Maglob, the basic approach is to test the conversion from string to date using SimpleDateFormat.parse. That will catch invalid day/month combinations like 2008-02-31.
However, in practice that is rarely enough since SimpleDateFormat.parse is exceedingly liberal. There are two behaviours you might be concerned with:
Invalid characters in the date string
Surprisingly, 2008-02-2x will "pass" as a valid date with locale format = "yyyy-MM-dd" for example. Even when isLenient==false.
Years: 2, 3 or 4 digits?
You may also want to enforce 4-digit years rather than allowing the default SimpleDateFormat behaviour (which will interpret "12-02-31" differently depending on whether your format was "yyyy-MM-dd" or "yy-MM-dd")
A Strict Solution with the Standard Library
So a complete string to date test could look like this: a combination of regex match, and then a forced date conversion. The trick with the regex is to make it locale-friendly.
Date parseDate(String maybeDate, String format, boolean lenient) {
Date date = null;
// test date string matches format structure using regex
// - weed out illegal characters and enforce 4-digit year
// - create the regex based on the local format string
String reFormat = Pattern.compile("d+|M+").matcher(Matcher.quoteReplacement(format)).replaceAll("\\\\d{1,2}");
reFormat = Pattern.compile("y+").matcher(reFormat).replaceAll("\\\\d{4}");
if ( Pattern.compile(reFormat).matcher(maybeDate).matches() ) {
// date string matches format structure,
// - now test it can be converted to a valid date
SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance();
sdf.applyPattern(format);
sdf.setLenient(lenient);
try { date = sdf.parse(maybeDate); } catch (ParseException e) { }
}
return date;
}
// used like this:
Date date = parseDate( "21/5/2009", "d/M/yyyy", false);
Note that the regex assumes the format string contains only day, month, year, and separator characters. Aside from that, format can be in any locale format: "d/MM/yy", "yyyy-MM-dd", and so on. The format string for the current locale could be obtained like this:
Locale locale = Locale.getDefault();
SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT, locale );
String format = sdf.toPattern();
Joda Time - Better Alternative?
I've been hearing about joda time recently and thought I'd compare. Two points:
Seems better at being strict about invalid characters in the date string, unlike SimpleDateFormat
Can't see a way to enforce 4-digit years with it yet (but I guess you could create your own DateTimeFormatter for this purpose)
It's quite simple to use:
import org.joda.time.format.*;
import org.joda.time.DateTime;
org.joda.time.DateTime parseDate(String maybeDate, String format) {
org.joda.time.DateTime date = null;
try {
DateTimeFormatter fmt = DateTimeFormat.forPattern(format);
date = fmt.parseDateTime(maybeDate);
} catch (Exception e) { }
return date;
}
tl;dr
Use the strict mode on java.time.DateTimeFormatter to parse a LocalDate. Trap for the DateTimeParseException.
LocalDate.parse( // Represent a date-only value, without time-of-day and without time zone.
"31/02/2000" , // Input string.
DateTimeFormatter // Define a formatting pattern to match your input string.
.ofPattern ( "dd/MM/uuuu" )
.withResolverStyle ( ResolverStyle.STRICT ) // Specify leniency in tolerating questionable inputs.
)
After parsing, you might check for reasonable value. For example, a birth date within last one hundred years.
birthDate.isAfter( LocalDate.now().minusYears( 100 ) )
Avoid legacy date-time classes
Avoid using the troublesome old date-time classes shipped with the earliest versions of Java. Now supplanted by the java.time classes.
LocalDate & DateTimeFormatter & ResolverStyle
The LocalDate class represents a date-only value without time-of-day and without time zone.
String input = "31/02/2000";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "dd/MM/uuuu" );
try {
LocalDate ld = LocalDate.parse ( input , f );
System.out.println ( "ld: " + ld );
} catch ( DateTimeParseException e ) {
System.out.println ( "ERROR: " + e );
}
The java.time.DateTimeFormatter class can be set to parse strings with any of three leniency modes defined in the ResolverStyle enum. We insert a line into the above code to try each of the modes.
f = f.withResolverStyle ( ResolverStyle.LENIENT );
The results:
ResolverStyle.LENIENTld: 2000-03-02
ResolverStyle.SMARTld: 2000-02-29
ResolverStyle.STRICTERROR: java.time.format.DateTimeParseException: Text '31/02/2000' could not be parsed: Invalid date 'FEBRUARY 31'
We can see that in ResolverStyle.LENIENT mode, the invalid date is moved forward an equivalent number of days. In ResolverStyle.SMART mode (the default), a logical decision is made to keep the date within the month and going with the last possible day of the month, Feb 29 in a leap year, as there is no 31st day in that month. The ResolverStyle.STRICT mode throws an exception complaining that there is no such date.
All three of these are reasonable depending on your business problem and policies. Sounds like in your case you want the strict mode to reject the invalid date rather than adjust it.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
You can use SimpleDateFormat
For example something like:
boolean isLegalDate(String s) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setLenient(false);
return sdf.parse(s, new ParsePosition(0)) != null;
}
The current way is to use the calendar class. It has the setLenient method that will validate the date and throw and exception if it is out of range as in your example.
Forgot to add:
If you get a calendar instance and set the time using your date, this is how you get the validation.
Calendar cal = Calendar.getInstance();
cal.setLenient(false);
cal.setTime(yourDate);
try {
cal.getTime();
}
catch (Exception e) {
System.out.println("Invalid date");
}
java.time
With the Date and Time API (java.time classes) built into Java 8 and later, you can use the LocalDate class.
public static boolean isDateValid(int year, int month, int day) {
try {
LocalDate.of(year, month, day);
} catch (DateTimeException e) {
return false;
}
return true;
}
Building on Aravind's answer to fix the problem pointed out by ceklock in his comment, I added a method to verify that the dateString doesn't contain any invalid character.
Here is how I do:
private boolean isDateCorrect(String dateString) {
try {
Date date = mDateFormatter.parse(dateString);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return matchesOurDatePattern(dateString); //added my method
}
catch (ParseException e) {
return false;
}
}
/**
* This will check if the provided string matches our date format
* #param dateString
* #return true if the passed string matches format 2014-1-15 (YYYY-MM-dd)
*/
private boolean matchesDatePattern(String dateString) {
return dateString.matches("^\\d+\\-\\d+\\-\\d+");
}
An alternative strict solution using the standard library is to perform the following:
1) Create a strict SimpleDateFormat using your pattern
2) Attempt to parse the user entered value using the format object
3) If successful, reformat the Date resulting from (2) using the same date format (from (1))
4) Compare the reformatted date against the original, user-entered value. If they're equal then the value entered strictly matches your pattern.
This way, you don't need to create complex regular expressions - in my case I needed to support all of SimpleDateFormat's pattern syntax, rather than be limited to certain types like just days, months and years.
I suggest you to use org.apache.commons.validator.GenericValidator class from apache.
GenericValidator.isDate(String value, String datePattern, boolean strict);
Note: strict - Whether or not to have an exact match of the datePattern.
I think the simpliest is just to convert a string into a date object and convert it back to a string. The given date string is fine if both strings still match.
public boolean isDateValid(String dateString, String pattern)
{
try
{
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
if (sdf.format(sdf.parse(dateString)).equals(dateString))
return true;
}
catch (ParseException pe) {}
return false;
}
Assuming that both of those are Strings (otherwise they'd already be valid Dates), here's one way:
package cruft;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateValidator
{
private static final DateFormat DEFAULT_FORMATTER;
static
{
DEFAULT_FORMATTER = new SimpleDateFormat("dd-MM-yyyy");
DEFAULT_FORMATTER.setLenient(false);
}
public static void main(String[] args)
{
for (String dateString : args)
{
try
{
System.out.println("arg: " + dateString + " date: " + convertDateString(dateString));
}
catch (ParseException e)
{
System.out.println("could not parse " + dateString);
}
}
}
public static Date convertDateString(String dateString) throws ParseException
{
return DEFAULT_FORMATTER.parse(dateString);
}
}
Here's the output I get:
java cruft.DateValidator 32-11-2010 31-02-2010 04-01-2011
could not parse 32-11-2010
could not parse 31-02-2010
arg: 04-01-2011 date: Tue Jan 04 00:00:00 EST 2011
Process finished with exit code 0
As you can see, it does handle both of your cases nicely.
This is working great for me. Approach suggested above by Ben.
private static boolean isDateValid(String s) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
Date d = asDate(s);
if (sdf.format(d).equals(s)) {
return true;
} else {
return false;
}
} catch (ParseException e) {
return false;
}
}
looks like SimpleDateFormat is not checking the pattern strictly even after setLenient(false); method is applied on it, so i have used below method to validate if the date inputted is valid date or not as per supplied pattern.
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public boolean isValidFormat(String dateString, String pattern) {
boolean valid = true;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
try {
formatter.parse(dateString);
} catch (DateTimeParseException e) {
valid = false;
}
return valid;
}
Two comments on the use of SimpleDateFormat.
it should be declared as a static instance
if declared as static access should be synchronized as it is not thread safe
IME that is better that instantiating an instance for each parse of a date.
Above methods of date parsing are nice , i just added new check in existing methods that double check the converted date with original date using formater, so it works for almost each case as i verified. e.g. 02/29/2013 is invalid date.
Given function parse the date according to current acceptable date formats. It returns true if date is not parsed successfully.
public final boolean validateDateFormat(final String date) {
String[] formatStrings = {"MM/dd/yyyy"};
boolean isInvalidFormat = false;
Date dateObj;
for (String formatString : formatStrings) {
try {
SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getDateInstance();
sdf.applyPattern(formatString);
sdf.setLenient(false);
dateObj = sdf.parse(date);
System.out.println(dateObj);
if (date.equals(sdf.format(dateObj))) {
isInvalidFormat = false;
break;
}
} catch (ParseException e) {
isInvalidFormat = true;
}
}
return isInvalidFormat;
}
Here's what I did for Node environment using no external libraries:
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return zeroPad([yyyy, mm, dd].join('-'));
};
function zeroPad(date_string) {
var dt = date_string.split('-');
return dt[0] + '-' + (dt[1][1]?dt[1]:"0"+dt[1][0]) + '-' + (dt[2][1]?dt[2]:"0"+dt[2][0]);
}
function isDateCorrect(in_string) {
if (!matchesDatePattern) return false;
in_string = zeroPad(in_string);
try {
var idate = new Date(in_string);
var out_string = idate.yyyymmdd();
return in_string == out_string;
} catch(err) {
return false;
}
function matchesDatePattern(date_string) {
var dateFormat = /[0-9]+-[0-9]+-[0-9]+/;
return dateFormat.test(date_string);
}
}
And here is how to use it:
isDateCorrect('2014-02-23')
true
// to return valid days of month, according to month and year
int returnDaysofMonth(int month, int year) {
int daysInMonth;
boolean leapYear;
leapYear = checkLeap(year);
if (month == 4 || month == 6 || month == 9 || month == 11)
daysInMonth = 30;
else if (month == 2)
daysInMonth = (leapYear) ? 29 : 28;
else
daysInMonth = 31;
return daysInMonth;
}
// to check a year is leap or not
private boolean checkLeap(int year) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
}
Here is I would check the date format:
public static boolean checkFormat(String dateTimeString) {
return dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}") || dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}")
|| dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}") || dateTimeString
.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z") ||
dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}Z");
}
public static String detectDateFormat(String inputDate, String requiredFormat) {
String tempDate = inputDate.replace("/", "").replace("-", "").replace(" ", "");
String dateFormat;
if (tempDate.matches("([0-12]{2})([0-31]{2})([0-9]{4})")) {
dateFormat = "MMddyyyy";
} else if (tempDate.matches("([0-31]{2})([0-12]{2})([0-9]{4})")) {
dateFormat = "ddMMyyyy";
} else if (tempDate.matches("([0-9]{4})([0-12]{2})([0-31]{2})")) {
dateFormat = "yyyyMMdd";
} else if (tempDate.matches("([0-9]{4})([0-31]{2})([0-12]{2})")) {
dateFormat = "yyyyddMM";
} else if (tempDate.matches("([0-31]{2})([a-z]{3})([0-9]{4})")) {
dateFormat = "ddMMMyyyy";
} else if (tempDate.matches("([a-z]{3})([0-31]{2})([0-9]{4})")) {
dateFormat = "MMMddyyyy";
} else if (tempDate.matches("([0-9]{4})([a-z]{3})([0-31]{2})")) {
dateFormat = "yyyyMMMdd";
} else if (tempDate.matches("([0-9]{4})([0-31]{2})([a-z]{3})")) {
dateFormat = "yyyyddMMM";
} else {
return "Pattern Not Added";
//add your required regex
}
try {
String formattedDate = new SimpleDateFormat(requiredFormat, Locale.ENGLISH).format(new SimpleDateFormat(dateFormat).parse(tempDate));
return formattedDate;
} catch (Exception e) {
//
return "";
}
}
setLenient to false if you like a strict validation
public boolean isThisDateValid(String dateToValidate, String dateFromat){
if(dateToValidate == null){
return false;
}
SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
sdf.setLenient(false);
try {
//if not valid, it will throw ParseException
Date date = sdf.parse(dateToValidate);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
return false;
}
return true;
}
With 'legacy' date format, we can format the result and compare it back to the source.
public boolean isValidFormat(String source, String pattern) {
SimpleDateFormat sd = new SimpleDateFormat(pattern);
sd.setLenient(false);
try {
Date date = sd.parse(source);
return date != null && sd.format(date).equals(source);
} catch (Exception e) {
return false;
}
}
This execerpt says 'false' to source=01.01.04 with pattern '01.01.2004'
We can use the org.apache.commons.validator.GenericValidator's method directly without adding the whole library:
public static boolean isValidDate(String value, String datePattern, boolean strict) {
if (value == null
|| datePattern == null
|| datePattern.length() <= 0) {
return false;
}
SimpleDateFormat formatter = new SimpleDateFormat(datePattern, Locale.ENGLISH);
formatter.setLenient(false);
try {
formatter.parse(value);
} catch(ParseException e) {
return false;
}
if (strict && (datePattern.length() != value.length())) {
return false;
}
return true;
}
A simple and elegant way for Android developers (Java 8 not required):
// month value is 1-based. e.g., 1 for January.
public static boolean isDateValid(int year, int month, int day) {
Calendar calendar = Calendar.getInstance();
try {
calendar.setLenient(false);
calendar.set(year, month-1, day);
calendar.getTime();
return true;
} catch (Exception e) {
return false;
}
}
Below code works with dd/MM/yyyy format and can be used to check NotNull,NotEmpty as well.
public static boolean validateJavaDate(String strDate) {
if (strDate != null && !strDate.isEmpty() && !strDate.equalsIgnoreCase(" ")) {
{
SimpleDateFormat date = new SimpleDateFormat("dd/MM/yyyy");
date.setLenient(false);
try {
Date javaDate = date.parse(strDate);
System.out.println(strDate + " Valid Date format");
}
catch (ParseException e) {
System.out.println(strDate + " Invalid Date format");
return false;
}
return true;
}
} else {
System.out.println(strDate + "----> Date is Null/Empty");
return false;
}
}
This question already has answers here:
Get first date of current month in java
(11 answers)
Closed 4 years ago.
I can convert a String to a Date:
private static final SimpleDateFormat CARD_DATE_FORMAT = new SimpleDateFormat("yyMMdd", Locale.getDefault());
public static Date toCardDateFormat(String date){
try {
return CARD_DATE_FORMAT.parse(date);
} catch (ParseException e) {
return null;
}
}
For example I have 200908 - it will convert to 2020-09-08, but I need set the day always to 1st day of month. I need 2020-09-01. How can I make this?
According to your need,you can use this method:
private static final SimpleDateFormat CARD_DATE_FORMAT = new SimpleDateFormat("yyMMdd", Locale.getDefault());
public static String toCardDateFormat(String date) {
try {
Date value = CARD_DATE_FORMAT.parse(date);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yy-MM", Locale.getDefault());
String datetimeLocale = dateFormatter.format(value);
String newDate = datetimeLocale + "-01";
return newDate;
} catch (ParseException e) {
return null;
}
}
for date object you can use this:
public static Date toCardDateFormat(String date) {
try {
Date value = CARD_DATE_FORMAT.parse(date);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yy-MM", Locale.getDefault());
String datetimeLocale = dateFormatter.format(value);
String newDate = datetimeLocale + "-01";
SimpleDateFormat dateFormat = new SimpleDateFormat("yy-MM-dd",Locale.getDefault());
Date d = dateFormat.parse(newDate);
return d;
} catch (ParseException e) {
return null;
}
}
Maciej's answer is correct, but if you use Java 8 or higher, it's better to use the java.time classes:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMdd");
// parse and change the day of month
LocalDate d = LocalDate.parse("200908", formatter).withDayOfMonth(1);
System.out.println(d); // 2020-09-01
Note that the LocalDate is printed in the format you want - which is ISO8601 compliant. If you want a different format, just use another DateTimeFormatter and call the format method.
Manually changing the string, as suggested by others, might also work, but if you're dealing with dates, why not use a proper date-handling API? Direct string manipulation won't help you in cases like invalid dates (the formatter will throw an exception for invalid inputs), or if you try to change the day to invalid values (such as day 31 for April, or 29 for February in a non-leap year, which are checked by the API and throw an exception if the value is invalid).
Your code has multi threading issue, best create locally in your convert function to avoid it (otherwise you will have troubles with multiple thread as this class is not thread-safe)
Answer to your question is (using old Date api) - you can use Calendar to do it:
public static Date toCardDateFormat(String date){
Date result = null;
try {
result = new SimpleDateFormat("yyMMdd", Locale.getDefault()).parse(date);
} catch (ParseException e) {
return null; // or better throw exception or return Optional.empty()
}
Calendar cal = Calendar.getInstance();
cal.setTime(result);
cal.set(Calendar.DAY_OF_MONTH, 1);
return cal.getTime();
}
you could try something like this:
String[] arr = date.split("-");
String newDate = arr[0] + "-" + arr[1] + "-01";
private static final DateTimeFormatter CARD_DATE_FORMAT
= DateTimeFormatter.ofPattern("yyMMdd", Locale.getDefault());
public static Optional<YearMonth> toCardDateFormat(String date) {
try {
return Optional.of(YearMonth.parse(date, CARD_DATE_FORMAT));
} catch (DateTimeParseException e) {
return Optional.empty();
}
}
Don’t return null from a method. The risk of a NullPointerException on the caller’s side would be great. If you believe that not returning a value is the right thing in case of a string in the wrong format or containing an invalid date, use Optional to force the caller to take the possibility of no return value into account. Another obvious option is to leave any parsing exception to the caller:
public static YearMonth toCardDateFormat(String date) {
return YearMonth.parse(date, CARD_DATE_FORMAT);
}
DateTimeParseException is an unchecked exception, so needs not be declared in the method signature. Let’s try it:
System.out.println(toCardDateFormat("200908"));
This prints:
2020-09
Other messages:
I am using and warmly recommending java.time, the modern Java date and time API. The old date-time classes from Java 1.0 and 1.1 are now long outdated, and SimpleDateFormat in particular is notoriously troublesome. I think you should avoid them. The modern API is so much nicer to work with.
It seems you would really prefer to remove the day of month so you only have the month and year? The YearMonth class from java.time does exactly that for you. If instead you wanted a full date, use the LocalDate class as in xunts’ answer.
Link: Oracle tutorial: Date Time explaining how to use java.time.
I want to return the message "Date is very wrong" if the transaction date is greater than the computation date. Instead, it just prints "-1 days".
import java.text.SimpleDateFormat;
import java.util.Date;
public class Age {
public static long computeAge(String transDate, String computeDate){
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
long lapseDays = 0;
try {
Date TDate = format.parse(transDate);
Date CDate = format.parse(computeDate);
long aging = CDate.getTime() - TDate.getTime();
lapseDays = aging/(24*60*60*1000);
}catch (Exception e){
e.printStackTrace();
System.out.print("Date is very wrong");
}
return lapseDays;
}
public static void main(String[] args) {
String transaction = "10/01/2014";
String computation = "09/30/2014";
System.out.println(computeAge(transaction, computation)+ " days");
}
}
If I understand your question, you could call the method Date.after(Date) and something like
Date TDate = format.parse(transDate);
Date CDate = format.parse(computeDate);
if (TDate.after(CDate)) {
System.out.print("Date is very wrong");
return -1;
}
try this: change the return type to String of computeAge() method.
public class Test2 {
public static String computeAge(String transDate, String computeDate){
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
long lapseDays = 0;
try {
Date TDate = format.parse(transDate);
Date CDate = format.parse(computeDate);
long aging = CDate.getTime() - TDate.getTime();
lapseDays = aging/(24*60*60*1000);
if(lapseDays<0){
return "Date is very wrong";
}
}catch (Exception e){
e.printStackTrace();
System.out.print("Date is very wrong");
}
return lapseDays+" days";
}
public static void main(String[] args) {
String transaction = "10/01/2014";
String computation = "09/30/2014";
System.out.println(computeAge(transaction, computation));
}
}
Joda-Time
Here is some easier code, using the Joda-Time library version 2.4. Joda-Time is far superior to the confusing and troublesome java.util.Date & .Calendar classes bundled with Java.
LocalDate
In particular, Joda-Time offers a class to represent a date-only without time-of-day or time zone, LocalDate.
The java.time package built into Java 8 (inspired by Joda-Time) also offers a LocalDate class.
Test For All Outcomes
The question may be confusing three possible outcomes, and fails to test for the second:
Either string input is invalid format, and cannot be parsed. (bad)
The first date may occur after the second date, or is equal. (bad)
The first date occurs before the second date. (good)
For more robust code, you should also do sanity-checks on the data, looking for dates that are too far in the past or in the future.
Give Better Feedback
Note that I use different messages for each possible outcome. The code in the Question uses identical messages which leads to confusion.
Example Code
Invalid string inputs are detected during parsing by throwing the Joda-Time exception, IllegalArgumentException.
String inputA = "10/01/2014";
String inputB = "09/30/2014";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy" );
try {
LocalDate a = formatter.parseLocalDate( inputA );
LocalDate b = formatter.parseLocalDate( inputB );
int daysBetween = Days.daysBetween( a , b ).getDays();
if ( a.isBefore( b ) ) {
System.out.println( "First date is " + daysBetween + " days before second date." );
} else { // Else the same date or a is later than b.
System.out.println( "Error: First date is same or later than second date." );
}
} catch ( IllegalArgumentException e ) {
System.out.println( "Invalid date string." );
}
I find it curious that the most obvious way to create Date objects in Java has been deprecated and appears to have been "substituted" with a not so obvious to use lenient calendar.
How do you check that a date, given as a combination of day, month, and year, is a valid date?
For instance, 2008-02-31 (as in yyyy-mm-dd) would be an invalid date.
Key is df.setLenient(false);. This is more than enough for simple cases. If you are looking for a more robust (I doubt that) and/or alternate libraries like joda-time, then look at the answer by user "tardate"
final static String DATE_FORMAT = "dd-MM-yyyy";
public static boolean isDateValid(String date)
{
try {
DateFormat df = new SimpleDateFormat(DATE_FORMAT);
df.setLenient(false);
df.parse(date);
return true;
} catch (ParseException e) {
return false;
}
}
As shown by #Maglob, the basic approach is to test the conversion from string to date using SimpleDateFormat.parse. That will catch invalid day/month combinations like 2008-02-31.
However, in practice that is rarely enough since SimpleDateFormat.parse is exceedingly liberal. There are two behaviours you might be concerned with:
Invalid characters in the date string
Surprisingly, 2008-02-2x will "pass" as a valid date with locale format = "yyyy-MM-dd" for example. Even when isLenient==false.
Years: 2, 3 or 4 digits?
You may also want to enforce 4-digit years rather than allowing the default SimpleDateFormat behaviour (which will interpret "12-02-31" differently depending on whether your format was "yyyy-MM-dd" or "yy-MM-dd")
A Strict Solution with the Standard Library
So a complete string to date test could look like this: a combination of regex match, and then a forced date conversion. The trick with the regex is to make it locale-friendly.
Date parseDate(String maybeDate, String format, boolean lenient) {
Date date = null;
// test date string matches format structure using regex
// - weed out illegal characters and enforce 4-digit year
// - create the regex based on the local format string
String reFormat = Pattern.compile("d+|M+").matcher(Matcher.quoteReplacement(format)).replaceAll("\\\\d{1,2}");
reFormat = Pattern.compile("y+").matcher(reFormat).replaceAll("\\\\d{4}");
if ( Pattern.compile(reFormat).matcher(maybeDate).matches() ) {
// date string matches format structure,
// - now test it can be converted to a valid date
SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance();
sdf.applyPattern(format);
sdf.setLenient(lenient);
try { date = sdf.parse(maybeDate); } catch (ParseException e) { }
}
return date;
}
// used like this:
Date date = parseDate( "21/5/2009", "d/M/yyyy", false);
Note that the regex assumes the format string contains only day, month, year, and separator characters. Aside from that, format can be in any locale format: "d/MM/yy", "yyyy-MM-dd", and so on. The format string for the current locale could be obtained like this:
Locale locale = Locale.getDefault();
SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT, locale );
String format = sdf.toPattern();
Joda Time - Better Alternative?
I've been hearing about joda time recently and thought I'd compare. Two points:
Seems better at being strict about invalid characters in the date string, unlike SimpleDateFormat
Can't see a way to enforce 4-digit years with it yet (but I guess you could create your own DateTimeFormatter for this purpose)
It's quite simple to use:
import org.joda.time.format.*;
import org.joda.time.DateTime;
org.joda.time.DateTime parseDate(String maybeDate, String format) {
org.joda.time.DateTime date = null;
try {
DateTimeFormatter fmt = DateTimeFormat.forPattern(format);
date = fmt.parseDateTime(maybeDate);
} catch (Exception e) { }
return date;
}
tl;dr
Use the strict mode on java.time.DateTimeFormatter to parse a LocalDate. Trap for the DateTimeParseException.
LocalDate.parse( // Represent a date-only value, without time-of-day and without time zone.
"31/02/2000" , // Input string.
DateTimeFormatter // Define a formatting pattern to match your input string.
.ofPattern ( "dd/MM/uuuu" )
.withResolverStyle ( ResolverStyle.STRICT ) // Specify leniency in tolerating questionable inputs.
)
After parsing, you might check for reasonable value. For example, a birth date within last one hundred years.
birthDate.isAfter( LocalDate.now().minusYears( 100 ) )
Avoid legacy date-time classes
Avoid using the troublesome old date-time classes shipped with the earliest versions of Java. Now supplanted by the java.time classes.
LocalDate & DateTimeFormatter & ResolverStyle
The LocalDate class represents a date-only value without time-of-day and without time zone.
String input = "31/02/2000";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "dd/MM/uuuu" );
try {
LocalDate ld = LocalDate.parse ( input , f );
System.out.println ( "ld: " + ld );
} catch ( DateTimeParseException e ) {
System.out.println ( "ERROR: " + e );
}
The java.time.DateTimeFormatter class can be set to parse strings with any of three leniency modes defined in the ResolverStyle enum. We insert a line into the above code to try each of the modes.
f = f.withResolverStyle ( ResolverStyle.LENIENT );
The results:
ResolverStyle.LENIENTld: 2000-03-02
ResolverStyle.SMARTld: 2000-02-29
ResolverStyle.STRICTERROR: java.time.format.DateTimeParseException: Text '31/02/2000' could not be parsed: Invalid date 'FEBRUARY 31'
We can see that in ResolverStyle.LENIENT mode, the invalid date is moved forward an equivalent number of days. In ResolverStyle.SMART mode (the default), a logical decision is made to keep the date within the month and going with the last possible day of the month, Feb 29 in a leap year, as there is no 31st day in that month. The ResolverStyle.STRICT mode throws an exception complaining that there is no such date.
All three of these are reasonable depending on your business problem and policies. Sounds like in your case you want the strict mode to reject the invalid date rather than adjust it.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
You can use SimpleDateFormat
For example something like:
boolean isLegalDate(String s) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setLenient(false);
return sdf.parse(s, new ParsePosition(0)) != null;
}
The current way is to use the calendar class. It has the setLenient method that will validate the date and throw and exception if it is out of range as in your example.
Forgot to add:
If you get a calendar instance and set the time using your date, this is how you get the validation.
Calendar cal = Calendar.getInstance();
cal.setLenient(false);
cal.setTime(yourDate);
try {
cal.getTime();
}
catch (Exception e) {
System.out.println("Invalid date");
}
java.time
With the Date and Time API (java.time classes) built into Java 8 and later, you can use the LocalDate class.
public static boolean isDateValid(int year, int month, int day) {
try {
LocalDate.of(year, month, day);
} catch (DateTimeException e) {
return false;
}
return true;
}
Building on Aravind's answer to fix the problem pointed out by ceklock in his comment, I added a method to verify that the dateString doesn't contain any invalid character.
Here is how I do:
private boolean isDateCorrect(String dateString) {
try {
Date date = mDateFormatter.parse(dateString);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return matchesOurDatePattern(dateString); //added my method
}
catch (ParseException e) {
return false;
}
}
/**
* This will check if the provided string matches our date format
* #param dateString
* #return true if the passed string matches format 2014-1-15 (YYYY-MM-dd)
*/
private boolean matchesDatePattern(String dateString) {
return dateString.matches("^\\d+\\-\\d+\\-\\d+");
}
An alternative strict solution using the standard library is to perform the following:
1) Create a strict SimpleDateFormat using your pattern
2) Attempt to parse the user entered value using the format object
3) If successful, reformat the Date resulting from (2) using the same date format (from (1))
4) Compare the reformatted date against the original, user-entered value. If they're equal then the value entered strictly matches your pattern.
This way, you don't need to create complex regular expressions - in my case I needed to support all of SimpleDateFormat's pattern syntax, rather than be limited to certain types like just days, months and years.
I suggest you to use org.apache.commons.validator.GenericValidator class from apache.
GenericValidator.isDate(String value, String datePattern, boolean strict);
Note: strict - Whether or not to have an exact match of the datePattern.
I think the simpliest is just to convert a string into a date object and convert it back to a string. The given date string is fine if both strings still match.
public boolean isDateValid(String dateString, String pattern)
{
try
{
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
if (sdf.format(sdf.parse(dateString)).equals(dateString))
return true;
}
catch (ParseException pe) {}
return false;
}
Assuming that both of those are Strings (otherwise they'd already be valid Dates), here's one way:
package cruft;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateValidator
{
private static final DateFormat DEFAULT_FORMATTER;
static
{
DEFAULT_FORMATTER = new SimpleDateFormat("dd-MM-yyyy");
DEFAULT_FORMATTER.setLenient(false);
}
public static void main(String[] args)
{
for (String dateString : args)
{
try
{
System.out.println("arg: " + dateString + " date: " + convertDateString(dateString));
}
catch (ParseException e)
{
System.out.println("could not parse " + dateString);
}
}
}
public static Date convertDateString(String dateString) throws ParseException
{
return DEFAULT_FORMATTER.parse(dateString);
}
}
Here's the output I get:
java cruft.DateValidator 32-11-2010 31-02-2010 04-01-2011
could not parse 32-11-2010
could not parse 31-02-2010
arg: 04-01-2011 date: Tue Jan 04 00:00:00 EST 2011
Process finished with exit code 0
As you can see, it does handle both of your cases nicely.
This is working great for me. Approach suggested above by Ben.
private static boolean isDateValid(String s) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
Date d = asDate(s);
if (sdf.format(d).equals(s)) {
return true;
} else {
return false;
}
} catch (ParseException e) {
return false;
}
}
looks like SimpleDateFormat is not checking the pattern strictly even after setLenient(false); method is applied on it, so i have used below method to validate if the date inputted is valid date or not as per supplied pattern.
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public boolean isValidFormat(String dateString, String pattern) {
boolean valid = true;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
try {
formatter.parse(dateString);
} catch (DateTimeParseException e) {
valid = false;
}
return valid;
}
Two comments on the use of SimpleDateFormat.
it should be declared as a static instance
if declared as static access should be synchronized as it is not thread safe
IME that is better that instantiating an instance for each parse of a date.
Above methods of date parsing are nice , i just added new check in existing methods that double check the converted date with original date using formater, so it works for almost each case as i verified. e.g. 02/29/2013 is invalid date.
Given function parse the date according to current acceptable date formats. It returns true if date is not parsed successfully.
public final boolean validateDateFormat(final String date) {
String[] formatStrings = {"MM/dd/yyyy"};
boolean isInvalidFormat = false;
Date dateObj;
for (String formatString : formatStrings) {
try {
SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getDateInstance();
sdf.applyPattern(formatString);
sdf.setLenient(false);
dateObj = sdf.parse(date);
System.out.println(dateObj);
if (date.equals(sdf.format(dateObj))) {
isInvalidFormat = false;
break;
}
} catch (ParseException e) {
isInvalidFormat = true;
}
}
return isInvalidFormat;
}
Here's what I did for Node environment using no external libraries:
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return zeroPad([yyyy, mm, dd].join('-'));
};
function zeroPad(date_string) {
var dt = date_string.split('-');
return dt[0] + '-' + (dt[1][1]?dt[1]:"0"+dt[1][0]) + '-' + (dt[2][1]?dt[2]:"0"+dt[2][0]);
}
function isDateCorrect(in_string) {
if (!matchesDatePattern) return false;
in_string = zeroPad(in_string);
try {
var idate = new Date(in_string);
var out_string = idate.yyyymmdd();
return in_string == out_string;
} catch(err) {
return false;
}
function matchesDatePattern(date_string) {
var dateFormat = /[0-9]+-[0-9]+-[0-9]+/;
return dateFormat.test(date_string);
}
}
And here is how to use it:
isDateCorrect('2014-02-23')
true
// to return valid days of month, according to month and year
int returnDaysofMonth(int month, int year) {
int daysInMonth;
boolean leapYear;
leapYear = checkLeap(year);
if (month == 4 || month == 6 || month == 9 || month == 11)
daysInMonth = 30;
else if (month == 2)
daysInMonth = (leapYear) ? 29 : 28;
else
daysInMonth = 31;
return daysInMonth;
}
// to check a year is leap or not
private boolean checkLeap(int year) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
}
Here is I would check the date format:
public static boolean checkFormat(String dateTimeString) {
return dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}") || dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}")
|| dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}") || dateTimeString
.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z") ||
dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}Z");
}
public static String detectDateFormat(String inputDate, String requiredFormat) {
String tempDate = inputDate.replace("/", "").replace("-", "").replace(" ", "");
String dateFormat;
if (tempDate.matches("([0-12]{2})([0-31]{2})([0-9]{4})")) {
dateFormat = "MMddyyyy";
} else if (tempDate.matches("([0-31]{2})([0-12]{2})([0-9]{4})")) {
dateFormat = "ddMMyyyy";
} else if (tempDate.matches("([0-9]{4})([0-12]{2})([0-31]{2})")) {
dateFormat = "yyyyMMdd";
} else if (tempDate.matches("([0-9]{4})([0-31]{2})([0-12]{2})")) {
dateFormat = "yyyyddMM";
} else if (tempDate.matches("([0-31]{2})([a-z]{3})([0-9]{4})")) {
dateFormat = "ddMMMyyyy";
} else if (tempDate.matches("([a-z]{3})([0-31]{2})([0-9]{4})")) {
dateFormat = "MMMddyyyy";
} else if (tempDate.matches("([0-9]{4})([a-z]{3})([0-31]{2})")) {
dateFormat = "yyyyMMMdd";
} else if (tempDate.matches("([0-9]{4})([0-31]{2})([a-z]{3})")) {
dateFormat = "yyyyddMMM";
} else {
return "Pattern Not Added";
//add your required regex
}
try {
String formattedDate = new SimpleDateFormat(requiredFormat, Locale.ENGLISH).format(new SimpleDateFormat(dateFormat).parse(tempDate));
return formattedDate;
} catch (Exception e) {
//
return "";
}
}
setLenient to false if you like a strict validation
public boolean isThisDateValid(String dateToValidate, String dateFromat){
if(dateToValidate == null){
return false;
}
SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
sdf.setLenient(false);
try {
//if not valid, it will throw ParseException
Date date = sdf.parse(dateToValidate);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
return false;
}
return true;
}
With 'legacy' date format, we can format the result and compare it back to the source.
public boolean isValidFormat(String source, String pattern) {
SimpleDateFormat sd = new SimpleDateFormat(pattern);
sd.setLenient(false);
try {
Date date = sd.parse(source);
return date != null && sd.format(date).equals(source);
} catch (Exception e) {
return false;
}
}
This execerpt says 'false' to source=01.01.04 with pattern '01.01.2004'
We can use the org.apache.commons.validator.GenericValidator's method directly without adding the whole library:
public static boolean isValidDate(String value, String datePattern, boolean strict) {
if (value == null
|| datePattern == null
|| datePattern.length() <= 0) {
return false;
}
SimpleDateFormat formatter = new SimpleDateFormat(datePattern, Locale.ENGLISH);
formatter.setLenient(false);
try {
formatter.parse(value);
} catch(ParseException e) {
return false;
}
if (strict && (datePattern.length() != value.length())) {
return false;
}
return true;
}
A simple and elegant way for Android developers (Java 8 not required):
// month value is 1-based. e.g., 1 for January.
public static boolean isDateValid(int year, int month, int day) {
Calendar calendar = Calendar.getInstance();
try {
calendar.setLenient(false);
calendar.set(year, month-1, day);
calendar.getTime();
return true;
} catch (Exception e) {
return false;
}
}
Below code works with dd/MM/yyyy format and can be used to check NotNull,NotEmpty as well.
public static boolean validateJavaDate(String strDate) {
if (strDate != null && !strDate.isEmpty() && !strDate.equalsIgnoreCase(" ")) {
{
SimpleDateFormat date = new SimpleDateFormat("dd/MM/yyyy");
date.setLenient(false);
try {
Date javaDate = date.parse(strDate);
System.out.println(strDate + " Valid Date format");
}
catch (ParseException e) {
System.out.println(strDate + " Invalid Date format");
return false;
}
return true;
}
} else {
System.out.println(strDate + "----> Date is Null/Empty");
return false;
}
}