SimpleDateFormat and Date Comparison not given correct ouput - java

try {
Date sysDate = new SimpleDateFormat("dd/mm/yyyy").parse(_sysDate);
Date userDate = new SimpleDateFormat("dd/mm/yyyy").parse(_userDate);
if (userDate.compareTo(sysDate) > 0)
return false;
else
return true;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Above is my following code snippet to check two dates which is greater or not.
When I am giving :
sysdate=12/9/2012 and userdate=11/9/2012 or 10/8/2012 or 15/9/2011 it is giving the correct output
But when I am giving :
sysdate=12/9/2012 and userdate=13/8/2012 or 15/7/2012 or 16/6/2012 it is giving incorrect output.
To my analysis I have come to this point if I choose any month between Jan' 12 to Aug '12 and select the day_of_month(i.e. 0,1,2,...,31) more than the current day_of_month (in this case 12), I always get an incorrect output.
Please suggest any possible solution.

The problem is the pattern which should be "dd/MM/yyyy" (with capital "MM" for month) instead of "dd/mm/yyyy" (with small "mm" which means minutes).
So, it should be as follows -
try {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date sysDate = df.parse(_sysDate);
Date userDate = df.parse(_userDate);
//...

try {
Date sysDate = new SimpleDateFormat("dd/MM/yyyy").parse(_sysDate);
Date userDate = new SimpleDateFormat("dd/MM/yyyy").parse(_userDate);
if (userDate.compareTo(sysDate) > 0)
return false;
else
return true;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The Date pattern is wrong dd/MM/yyyy instead of dd/mm/yyyy.

see this data format change like this dd/MM/yyyy in place of dd/mm/yyyy.
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

Related

Calculating the age of two LocalDates

Code:
public String Calcage(){
int age = 0;
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
Date birth = sdf.parse(dateOfBirth);
Date d = new Date();
LocalDate birthday = birth.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate now = d.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
age = Period.between(birthday, now).getYears();
} catch (ParseException e) {
e.printStackTrace();
}
return String.valueOf(age);
}
PROBLEM: It returns zero every time. The Date which I use for testing is 1985-01-07
If you are actually using 1985-01-07 it correctly returns 0 and should also throw a ParseException which will be caught from the catch block and the stacktrace will be printed.
Your code should work for 07.01.1985 and return 35.
if you want nevertheless to use 1985-01-07 you should edit the specified format to "yyyy-dd-MM" or "yyyy-MM-dd"

Exception while validating a date string in Java

I have found nice function which is validating the format and correctness of date String. I wanted to upgrade it to validate only >= 1900 years.
So this is what I found:
public boolean isDateValid(String date) {
try {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
df.setLenient(false);
df.parse(date);
return true;
} catch (ParseException e) {
return false;
}
}
And this is my upgraded version:
public boolean isDateValid(String date) {
try {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
df.setLenient(false);
df.parse(date);
Integer year = Integer.parseInt(date.substring(6, 10));
if (year>= 1900)
return true;
else
return false;
} catch (ParseException e) {
return false;
}
}
So instead of returning true I am checking if the year variable is greater or equal to 1900. The problem is when I run this function with "12-12-1xxx" (edit: or "12-12-1abc"). NumberFormatException is thrown while parsing year String to int. It definitely should not happen because ParseException should be thrown first, breaking the try {} block.
It looks like validation from first listing does not work properly because it accepts every "yyyy" part which begins with a number. Yet everything works fine for "12-12-xxxx" (edit: or "12-12-abcd").
EDIT:
Stop voting down my question and focus while you are reading. The question is very clear: why new SimpleDateFormat("dd-MM-yyyy").parse("12-12-1xxx") does not throw a ParseException?
As I understand from javadoc the SimpleDateFormat will take 1 as valid part of the year and will parse it. Instead you can try to validate date with regular expressions. You can find some examples here Regex to validate date format dd/mm/yyyy
The documentation of the parse method is:
Parses text from the beginning of the given string to produce a date.
The method may not use the entire text of the given string.
Because the whole string does not need to be used, then "12-12-1xxx" is actually parsed as "12-12-1", and you get a year 1 date.
Instead of using the substring, you could use the result of the parse method to get the year. getYear is depreciated and returns an offset from 1900 so you might want to convert to a Calendar or LocalDate first.
public boolean isDateValid(String date) {
try {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
df.setLenient(false);
Date parsed = df.parse(date);
int year = parsed.getYear() + 1900;
if (year >= 1900)
return true;
else
return false;
} catch (ParseException e) {
return false;
}
}
I have check your function, and find below details.
If you will pass 12-12-1xxx in main function then also you will get true it will not return false even when I print the date output which is converted by df.parse(date) is Oct 10 00:00:00 GMT 2.
So you will not get parse exception anytime for this,
Suggestion
Either you change ParseException by Exception or also use catch for NumberFormatException as below.
public boolean isDateValid(String date) {
try {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
df.setLenient(false);
df.parse(date);
Integer year = Integer.parseInt(date.substring(6, 10));
if (year>= 1900)
return true;
else
return false;
} catch (Exception e) { // Use Exception or if you want ParseException then use below commented code
return false;
}
/*catch (NumberFormatException nfe) { // Use this if you use ParseException
return false;
}*/
}
If anybody is interested in how the code should look like, here it is:
public boolean isDateValid(String date, String format) {
if (date.length()!=format.length())
return false;
try {
DateFormat df = new SimpleDateFormat(format);
df.setLenient(false);
df.parse(date); // exception is not thrown if day and month is
// correct AND the first char of year is a digit
// so if we have correct day and correct month
// and we know the year has 4 chars we can try to parse it
Integer year = Integer.parseInt(date.substring(6, 10));
if (year>= 1900 && year<=2015) // here we know that the year is 4 digit integer
return true; // and we can limit it
else
return false;
} catch (ParseException e) {
return false;
} catch (NumberFormatException e) {
return false;
}
}

Android parsing String to Date with SimpleDateFormat

I have String dateOrder= '2014-09-28' , i want to change format with SimpleDateFormat. but this is cannot formated.. how to solve ?
this my code
SimpleDateFormat date = new SimpleDateFormat("dd/MM/yy");
String dateOrder = fill_order_in.get(Variabel.KEY_DATE_ORDER);
try {
Date d = date.parse(dateOrder);
dateOrder = date.format(d);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try changing the first line to
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
You can use this for the parse. Then you need another SimpleDateFormat("dd/MM/yy") for formatting the new version.
The key point is that the parsing needs to be done with one pattern, and the formatting needs to be done with another. So rather than just creating one SimpleDateFormat instance, you need two, with different patterns: one for parsing, and one for formatting.
I believe you want something like this:
//first create an object that will parse your date as you have it ie 2014-09-28
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
String dateOrder = fill_order_in.get(Variabel.KEY_DATE_ORDER);
try {
Date d = date.parse(dateOrder);
//then use a different object to format the date as you want it ie 9/28/2014
dateOrder = new SimpleDateFormat("dd/MM/yy").format(d);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

parse string to date and time but not getting appropriate parsing

i am attaching the code. In this code i am taking a string which is a date from a flat text file. It consist of AM/PM(12 Hour Format). When i am parsing it, it is not parsing well not parsing in 24 hour format. I want the time difference b/w the current time and the string from file. And because of AM/PM its not converting in 24 hour format. So its showing same time difference whether it is PM or AM. So tell me any fruitful suggestion if you have. I ll be really thankful to you guys.
public class Casting {
/**
* #param args
*/
static FileReader fw;
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
fw = new FileReader("E://796F_log.txt");
BufferedReader pw =new BufferedReader(fw);
String last_Line_From_File="" ;
for (String message = pw.readLine(); message != null ; message = pw.readLine()) {
last_Line_From_File = message;
}
String[] array_Of_Data = last_Line_From_File.split("\\s") ;
String time = array_Of_Data[0]+" "+array_Of_Data[1]+" "+array_Of_Data[2] ;
System.out.println(time);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a");
Calendar cal = Calendar.getInstance();
String current_time = dateFormat.format(cal.getTime());
Date d1 = dateFormat.parse(time);
Date d2 = dateFormat.parse(current_time);
long total_time = d2.getTime()-d1.getTime();
total_time /= 1000 ;
System.out.println("current time "+d2.getHours()+":"+d2.getMinutes()+":"+d2.getSeconds()+"\n"+d1.getHours()+":"+d1.getMinutes()+":"+d1.getSeconds());
if(total_time <= 500)
{
System.out.println("working "+total_time);
}
else
System.out.println("nt working "+total_time);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("did the smart thing or dumb thing");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("we did attempt closing");
}
}
}
}
The problem is your format:
"MM/dd/yyyy HH:mm:ss a"
The HH here means the 24-hour value. So it's expecting "19" for 7pm. It's almost always wrong to include both "HH" and "a" (the AM/PM designator) in the same format string.
You probably want either
"MM/dd/yyyy hh:mm:ss a"
or
"MM/dd/yyyy h:mm:ss a"
depending on whether you get things like "07:00:00 AM" or "7:00:00 AM".
If you're doing any significant amount of date/time work, I'd recommend using Joda Time instead of Date/Calendar, by the way.

Using SimpleDateFormat in a for loop on a list of objects

My app crashes whenever I try to do this:
for (CalendarEvent event : this.ListofEvents){
String myDate = new String(event.getDate());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
theDate = format.parse(myDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(theDate.getDate());
}
If I just print event.getDate() as a test, it displays all the dates. But when I try to format each date I'm assuming it locks up the phone resources. It's a fairly large List with many entries.
Perhaps there's a better method of getting the day, month, and year without taking up all the resources.
Why are you creating a DateFormat inside the loop? You create it, use it, and then it goes out of scope for GC in the next iteration.
Move it outside the loop:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
format.setLenient(false);
for (CalendarEvent event : this.ListofEvents){
// what does event.getDate() return? A java.util.Date? If yes, why are you doing this at all?
String myDate = new String(event.getDate());
try {
theDate = format.parse(myDate);
System.out.println(theDate.getDate());
} catch (ParseException e) {
e.printStackTrace();
}
}

Categories