I want to create a method to validate a date by using SimpleDateFormat.
If the date is valid(e.g. 02/09/2012 or 2/09/2012 or 02/9/2012), this method should return true.
But if the format of the date is wrong(e.g. 02/09/201X) or logically wrong(e.g. 32/09/2012), this method should return false.
I try to write this method like this:
private boolean isValidDate(String date) {
DateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
DateFormat df2 = new SimpleDateFormat("d-MM-yyyy");
DateFormat df3 = new SimpleDateFormat("dd-M-yyyy");
Date d = null;
String s = null;
try {
d = df1.parse(date);
}catch (Exception e1) {
try{
d = df2.parse(date);
}catch (Exception e2) {
try {
d= df3.parse(date);
}catch (Exception e3) {
return false;
}
s = df3.format(d);
return date.equals(s);
}
s = df2.format(d);
return date.equals(s);
}
s = df1.format(d);
return date.equals(s);
}
But if I validate a date, for instance, 2/09/2012, it returns false (actually it should return true). I have no idea why... Can anyone find what's the problem with my code, or this logic is totally wrong? Is there any better way to do this validation?
Your input is in the format 2/09/2012 not 2-09-2012, so your dateformat should be like below:
DateFormat df1 = new SimpleDateFormat("dd/MM/yyyy");
DateFormat df2 = new SimpleDateFormat("d/MM/yyyy");
DateFormat df3 = new SimpleDateFormat("dd/M/yyyy");
I think your code is fine (but not very scalable - try to do it in a for-loop in case you add more formats later).
The problem is that your format strings are wrong. Instead of dd-MM-yyyy you should have dd/MM/yyyy. The same goes for the rest of the formats:
DateFormat df1 = new SimpleDateFormat("dd/MM/yyyy");
DateFormat df2 = new SimpleDateFormat("d/MM/yyyy");
DateFormat df3 = new SimpleDateFormat("dd/M/yyyy");
The validation fails because / isn't -.
Add this additional check after parsing each string:
Tokenize the value of the date String
Then use the extracted day, month and year values to create a new Date object using GregorianCalendar
Compare this to the date object you created from parsing the date strings
If they match then you know that the input string contained a valid date format
Related
This question already has answers here:
Parse any date in Java
(6 answers)
Closed 5 years ago.
I'm trying to convert a date string to date object in java regardless of current system date format. Because I want to get my custom date format to store in database. The following is my code and please advice me the way.
public static String dateToString(String date){
if(date.equals("")) return "";
if(date == null || date.length() == 0){
return "";
}
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try {
Date l_date = format.parse(date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(l_date);
String year = String.format("%04d", calendar.get(Calendar.YEAR));
String month = String.format("%02d", calendar.get(Calendar.MONTH));
String day = String.format("%02d", calendar.get(Calendar.DATE));
return year + month + day;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
For SimpleDateFormat, it can only parse the format I heard coded.
dateToString("16/04/2015");
It can convert for above code. But, when I try with the following format
dateToString("Thursday, April 16, 2015");
I go Unparseable date: "Thursday, April 16, 2015" error.
You're trying to convert a String in EEEE, MMMM dd, yyyy format with the format of dd/MM/yyyy...
Start by using the correct format for the String you trying to convert, the use what ever format you want to convert it back...
SimpleDateFormat from = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
SimpleDateFormat to = new SimpleDateFormat("dd/MM/yyyy");
String value = to.format(from.parse(dateString));
Now you could use something like DateUtils.parseDate(String, String[]) which allows to supply a number of different formats, but is still limited to what you might know.
A better solution would be to store the Date value directly within the database.
You are passing wrong parameter to SimpleDateFormater
Use
SimpleDateFormat format = new SimpleDateFormat("EEEE, MMMM dd, yyyy") instead of SimpleDateFormat to = new SimpleDateFormat("dd/MM/yyyy");
It resolve your Unparseable date issue.
Try to use something like this:
public static String dateToString(String date){
if(date.equals("")) return "";
if(date == null || date.length() == 0){
return "";
}
SimpleDateFormat formatIn = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat formatOut = new SimpleDateFormat("yyyy-dd-MM");
try {
Date l_date = formatIn.parse(date);
String result = formatOut.format(l_date);
return result;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
but if you want to put some data into database you may also use instead String java.sql.Date
something like this:
SimpleDateFormat format = new SimpleDateFormat();
Connection conn = ...
PreparedStatement ps = conn.prepareStatement("...");
long lDate = format.parse(sDate).getTime();
java.sql.Date dDate = new java.sql.Date(lDate);
ps.setDate(1, dDate);
I have a date in the format dd-mm-yyyy format(inside my db).I need to convert it to dd-mm-yy format.I retrieved date from db and stored it inside a string.
String date=doc.getString("date");
for example: 05-19-1990
to
05-19-90.
That 1990 is not fully needed only 90 is needed.Using split() in java i tried some thing but it wont helps me.Can anyone please help.Any help will be highly appreciated.......
Use DateFormat for that issue:
DateFormat df = SimpleDateFormat("dd-MM-yyyy");
DateFormat df1 = SimpleDateFormat("dd-MM-yy");
df1.format(df.parse(date));
Try below code
try {
SimpleDateFormat sdf= new SimpleDateFormat("MM-dd-yy");
Date d = sdf.parse("05-19-1990");
System.out.println(sdf.format(d));
} catch (ParseException ex) {
ex.printStackTrace();
}
Use two SimpleDateFormats, one to parse it, one to format it..
SimpleDateFormat in = new SimpleDateFormat("MM-dd-yyyy");
Date inDate = in.parse(date); // 05-19-1990
SimpleDateFormat out = new SimpleDateFormat("MM-dd-yy");
String newDate = out.format(inDate);
or
SimpleDateFormat out = new SimpleDateFormat("dd-MM-yy");
String newDate = out.format(inDate);
If you really want 19-05-90 as per the title of your question ;)
Check java.text.SimpleDateFormat for more details
Try this..
DateFormat df2 = new SimpleDateFormat("dd-mm-yy");
String formattedDate2 = df2.format(theDate);
I am writing a converter method that would parse an xml string data to java objects. But i am not able to parse dates to date objects.
How to format this date string "2013-08-26T12:00:00.000" in the following way: "2013-08-26 12:00:00" to Date object in java?
Edited to add the below code snippet.
Here is what I tried to do.
public Object fromString(String str) {
DateFormat dateFormat = DateFormat.getDateInstance();
try {
Date date = dateFormat.parse(str);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
}
You should google these things first.
Here you go:
public static void main(String[] args) {
String inFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS";
String outFormat = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(inFormat);
try {
Date d = sdf.parse("2013-08-26T12:00:00.000");
sdf.applyPattern(outFormat);
System.out.println(sdf.format(d));
} catch (ParseException e) {
// handle appropriately
e.printStackTrace();
}
}
You can parse any Date-like string to Date object (as long as the the string represents a valid date) using http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
There is no point in re-formatting the String.
In order to process XML-date-time-strings which are allowed to be of variable precision (sometimes leaving out second- or fraction-part or timezone-offset) the use of SimpleDateFormat is not a good option because then you would only have one pattern. Not flexible.
Alternative for XML:
String xml = "2013-08-26T12:00:00.000"; // maybe optionally with additional timezone offset
javax.xml.datatype.DatatypeFactory factory = javax.xml.datatype.DatatypeFactory.newInstance();
XMLGregorianCalendar xmlGregCal = factory.newXMLGregorianCalendar(xml);
java.util.Date d = xmlGregCal.toGregorianCalendar().getTime();
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String output = outputFormat.format(d);
Watch also out for some overloaded methods to change the timezone settings for parsing and formatting - see the javadoc.
You may try this:
public static void main(String[] args) throws Exception {
String original = "2013-08-26T12:00:00.000";
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S").parse(original);
String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
System.out.printf("Before: %s\nAfter: %s\n", original, format);
}
OUTPUT:
Before: 2013-08-26T12:00:00.000
After: 2013-08-26 12:00:00
I get this date as a string from SOAP message
"2009-12-02T12:58:38.415+01:00"
Most i could i could identify and vary on subject was
to play with this format yyyy-MM-dd ? hh:mm:ss.????
I tried different combinations using SSS T z Z instead of '?"
DateFormat df = new SimpleDateFormat("... various formats ...");
System.out.println(df.parse("2009-12-02T12:58:38.415+01:00"));
but no success.
Any idea ?
Thanks
you have to change the timezone part. try this:
String a = "2009-12-02T12:58:38.415+01:00";
a = a.replaceFirst(":(?=\\d+$)", "");
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
System.out.println(df.parse(a));
I don't think this is possible using the standard Java date formatting.
Using joda-time this can be done using the following code:
DateTimeFormatterBuilder b = new DateTimeFormatterBuilder()
.appendYear(4, 4).appendLiteral('-').appendMonthOfYear(2).appendLiteral('-').appendDayOfMonth(2)
.appendLiteral('T')
.appendHourOfDay(2).appendLiteral(':').appendMinuteOfHour(2).appendLiteral(':').appendSecondOfMinute(2)
.appendLiteral('.').appendMillisOfSecond(3).appendTimeZoneOffset(null, true, 2, 2);
DateTimeFormatter dateTimeParser = b.toFormatter();
System.out.println(dateTimeParser.parseDateTime("2009-12-02T12:58:38.415+01:00"));
Try with the following.
String date = "2009-12-02T12:58:38.415+01:00";
int lastIndexOf = date.lastIndexOf(":");
if(lastIndexOf>=0){
date = date.substring(0,lastIndexOf)+date.substring(lastIndexOf+1);
}
System.out.println("~~~~~~date~~~~~"+date);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSSZ");
try {
sdf.parse(date);
System.out.println("....date..."+date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have a date in(string) in dd-mon-yyyy format and I want to compare this date with system date.
eg.
I have 12-OCT-2010
and I want to compere this with system date in same format
You can use the SystemDateFormat class to parse your String, for example
final DateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
final Date input = fmt.parse("12-OCT-2010");
if (input.before(new Date()) {
// do something
}
Note that SimpleDateFormat is not threadsafe, so needs to be wrapped in a ThreadLocal if you have more than one thread accessing your code.
You may also be interested in Joda, which provides a better date API
Use SimpleDateFormat http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
String d = "12-OCT-2010";
try {
Date formatted = f.parse(d);
Date sysDate = new Date();
System.out.println(formatted);
System.out.println(sysDate);
if(formatted.before(sysDate)){
System.out.println("Formatted Date is older");
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I would recommend using Joda Time. You can parse that String into a LocalDate object very simply, and then construct another LocalDate from the system clock. You can then compare these dates.
Using simpledateformat -
String df = "dd-MMM-yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(df);
Calendar cal = Calendar.getInstance();
/* system date */
String systemdate = sdf.format(cal.getTime());
/* the date you want to compare in string format */
String yourdate = "12-Oct-2010";
Date ydate = null;
try {
ydate = sdf.parse(yourdate);
} catch (ParseException e) {
e.printStackTrace();
}
yourdate = sdf.format(ydate);
System.out.println(systemdate.equals(yourdate) ? "true" : "false");