I have written the following code snippet:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setLenient(false);
currentString = currentString.trim();
try{
Date date = sdf.parse(currentString);
} catch (java.text.ParseException e) {
return "";
}
I am expecting it to parse the date in format yyyy-MM-dd ie. it should parse date like 2013-10-28.
Though it is working fine, it is also parsing wrong inputs like 2013-10-28aaab. Ideally it should throw the exception when such kind of illegal date is given.
How can I restrict such illegal Date Patterns?
use a regex to match the input
something like
"/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/"
Just check the String length. BTW, you should set lenient to true, otherwise non valid dates (2013-02-31) will be allowed.
Related
I need to Validate Date in a specified format where both the inputs will be given only in the runtime in JTextfield and will be changing dynamically. Below is the code I have tried:
Date dd = new Date();
DateFormat df = new SimpleDateFormat(Date_format_text.getText());
try {
df.setLenient(false);
Date d1 = df.parse(Lower_date_text.getText());
System.out.println("Correct");
validator_LD.setVisible(false);
} catch (ParseException p) {
validator_LD.setText("*Not in mentioned Format '" + df.format(dd) + "'");
validator_LD.setVisible(true);
System.out.println("Wrong");
}
The above is.. i get the Date specified and the format specified from the text field and try to parse according to the specified format. If it doesn't match it will throw exception.
But this is not working properly in some cases :
If I give the Date 02/01/20'and the Format - dd/MM/YYYY where it should throw an exception since I have given the year as 20 and the format is 'YYYY' but i doesn't give exception.
Kindly help me.. Thanks in advance
First, you may want to take a look at How to Use the Focus Subsystem, paying attention to Validating Input which might help.
Second, as pointed out by #eatSleepCode, you're not actually parsing the text of the field, but are simply formatting an existing Date, so it will never throw an exception...
simple_format = new SimpleDateFormat(Date_format_text.getText());
// This is simply formatting the dates...
String ss = simple_format.format(dates);
Instead, you need to use something more like...
String test = "02/01/20";
String format = "dd/MM/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setLenient(false);
try {
Date date = sdf.parse(test);
if (!sdf.format(date).equals(test)) {
throw new ParseException(test + " is not a valid format for " + format, 0);
}
} catch (ParseException ex) {
ex.printStackTrace();
}
What this does, is test's the parser capabilities of the formatter, but also checks the input against what the resulting parsed Date would be formatted to, if these don't match it throws a ParseException. This is the closes I've been able to get to a strict parser...
Also, YYYY used to represent the week in year, not the year...
I am trying to format dates entered by my application user using SimpleDateFormat but I always get an error:
01/28/2014java.text.ParseException: Unparseable date: "01/28/2014"
The code I am using to format the date is as follows:
Date rDate, dDate;
String Date1 = request.getParameter("Date1");
String Date2 = request.getParameter("Date2");
//Here the date get display for example as 01/29/2014 (i.e. MM/DD/YYYY)
System.out.println("Date1:: "+ Date1);
System.out.println("Date2:: "+ Date2);
SimpleDateFormat parseRDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat parseDDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
//#########Crashes in the next two lines#########...
rDate = (Date)parseRDate.parse(Date1);
dDate = (Date)parseDDate.parse(Date2);
} catch (ParseException e) {
e.printStackTrace();
}
Can someone please help me by telling me what I am doing wrong here?
Thanks for your time
You need to match the DateFormat pattern to your input String
SimpleDateFormat parseRDate = new SimpleDateFormat("MM/dd/yyyy");
Any idea how I can convert the format from MM/dd/YYYY to yyyy-MM-dd HH:mm:ss?
All you need to do is use a separate SimpleDateFormat instance for formatting
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(output.format(date1));
As you say, Date1 is of the form MM/dd/yyyy... but you're trying to parse it with a format of yyyy-MM-dd HH:mm:ss.
The pattern you parse to the SimpleDateFormat constructor has to match the format of the data itself. (What did you think you were specifying in the constructor?)
Note that the code you've provided isn't doing and formatting at all - just parsing.
You should also work out which time zone you're interested in, and which Locale. Personally I think it's clearer to specify both of those explicitly - even if you want the system default ones.
(If you're doing any significant amount of date/time work, you should also consider using Joda Time, which is a much more pleasant date/time API. I'd also consider more useful exception handling, and following Java naming conventions...)
You specify the format yyyy-MM-dd HH:mm:ss in the constructor and then accept a completely different format (MM/dd/yyyy) as input. You need to make the actual format match the expected format.
Examine the following (for comparison):
Date rDate, dDate;
SimpleDateFormat parseRDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat parseDDate = new SimpleDateFormat("MM/dd/yyyy");
try {
rDate = (Date)parseRDate.parse("2014-01-28 12:22:22");
dDate = (Date)parseDDate.parse("01/28/2014");
} catch (ParseException e) {
e.printStackTrace();
}
The string passed to the constructor is what tells SimpleDateFormat how to read the input you give it later.
I have a date value of the type "2013-03-28T15:16:58.000Z". I want to convert it to "dd-MMM-yyyy" format. For that, I have used the following code:
public static String getTime(String time)
{
try
{
String tim = time.replace("T", " ");
SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ", Locale.US);
SimpleDateFormat df2 = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
return df2.format(df1.parse(tim));
}
catch (ParseException e)
{
return null;
}
}
I got this solution from a variety of posts here in StackOverflow. But this code still returns null. Can anyone tell me why?
The null value is being returned from exception block due the first SimpleDateFormat returning null as a result of an invalid date format.
The Zpattern is used to denote timezone patterns. To accept a literal Z character, you need to surround the character with single quotes.
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS'Z'", Locale.US);
Also, you can do the same with the T character if you don't wish to do a manual replace:
Instead of
String tim = time.replace("T", " "); // remove
just use time and use:
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
It is returning null because it is catching a ParseException and you are telling it to return null. You should be at least print out the stacktrace and that should tell you why you are getting the ParseException.
It's throwing a ParseException parsing the string 2013-03-28 15:16:58.000Z.
Try getting rid of the Z [like you did with the T] and using a SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US)
I am trying to compare two dates in java. While the following code works fine, I would like to handle situations where there may be some alterations in the date format of the input dates.
For example, in the below code, the date format of the two dates are as yyyy/mm/dd hh:mm:ss am. But sometimes there are some additional white space/new line characters found in the input date and this causes exception.
java.text.ParseException: Unparseable date: "02/14/2013
07:00:00 AM"
The following is the code am trying to execute.
try
{
Date date1 = (Date)DATE_FORMAT_yyyy_mm_dd_hh_mm_ss.parse(slaTime); // usually the data comes as 2013/02/03 09:09:09 AM
Date date2 = (Date)DATE_FORMAT_yyyy_mm_dd_hh_mm_ss.parse(actualTime);// usually the data comes as 2013/02/03 09:06:09 AM
// a error occurs
if(date1.before(date2))
{
return "True";
}
else
{
return "False";
}
}
catch (ParseException e)
{
e.printStackTrace();
}
how to handle this?
One of the simplest solutions is to strip all whitespace from the String version of the date before you parse it. Alter your date format to not include any spaces (yyyy/MM/ddhh:mm:ssaaa), and use this to parse the stripped string.
final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/ddhh:mm:ssaaa");
final String dateStr = "02/14/2013 07:00:00" +
"\n AM";
Date failingDate = dateFormat.parse(dateStr);
Date passingDate = dateFormat.parse(dateStr.replaceAll("\\s",""));
For Month in year Use M instead of m
Correct date format would be yyyy/MM/dd hh:mm:ss aaa. And If there is any additional space or new line then you must remove it other wise it will failed to parse your string to date, your should exact match with format .
I would suggest you to remove all space and new line character then parse it.
you can use format like - yyyy/MM/ddhh:mm:ssaaa where there is no space. And replaceAll your space and new Line with empty String.
Date date = new SimpleDateFormat("yyyy/MM/ddhh:mm:ssaaa").parse("2013/02/1407:00:00AM");
and you actual code could be like -
dateString = dateString.replaceAll("\\s","");
SimpleDateFormat("yyyy/MM/ddhh:mm:ssaaa").parse(dateString);
Is there a good, strict date parser for Java? I have access to Joda-Time but I have yet to see this option. I found the "Is there a good date parser for Java" question, and while this is related it is sort of the opposite. Whereas that question was asking for a lenient, more fuzzy-logic and prone to human error parser, I would like a strict parser. For example, with both JodaTime (as far as I can tell) and simpleDateFormat, if you have a format "MM/dd/yyyy":
parse this: 40/40/4353
This becomes a valid date. I want a parser that knows that 40 is an invalid month and date. Surely some implementation of this exists in Java?
I don't see that Joda recognizes that as a valid date. Example:
strict = org.joda.time.format.DateTimeFormat.forPattern("MM/dd/yyyy")
try {
strict.parseDateTime('40/40/4353')
assert false
} catch (org.joda.time.IllegalFieldValueException e) {
assert 'Cannot parse "40/40/4353": Value 40 for monthOfYear must be in the range [1,12]' == e.message
}
As best as I can tell, neither does DateFormat with setLenient(false). Example:
try {
df = new java.text.SimpleDateFormat('MM/dd/yyyy')
df.setLenient(false)
df.parse('40/40/4353')
assert false
} catch (java.text.ParseException e) {
assert e.message =~ 'Unparseable'
}
Hope this helps!
A good way to do strict validation with DateFormat is re-formatting the parsed date and checking equality to the original string:
String myDateString = "87/88/9999";
Date myDate = dateFormat.parse(myDateString);
if (!myDateString.equals(df.format(myDate))){
throw new ParseException();
}
Works like a charm.
You can use the apache.commons.validator.routines.DateValidator to validate the date,if you do not want to use SimpleDateFormat.
Example :
public static Date validateDate(String value, String pattern) {
DateValidator validator = new DateValidator();
Date date = null;
if (pattern!=null) { //Pattern is passed
date = validator.validate(value, pattern);
} else {
date = validator.validate(value);
}
return date;
}
So if a null is returned it means that the date is not valid otherwise it's a valid date.This method is an alternative to using the SimpleDateFormat as you don't have to rely on exception being thrown to identify if it's a valid date or not.