Reputation: 6170
I have a DateTimehelper.class in which i have performed some date related operation and the code was working fine until i get issue from customer that they are getting date in wrong format.following is my class:
public class DateTimeHelper {
private static Calendar cal;
public static DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static DateFormat shortDateFormatter = new SimpleDateFormat("yyyy-MM-dd");
public static DateFormat shortDateFormatterWithSlash = new SimpleDateFormat("dd/MM/yyyy");
public static DateFormat dateFormat_dd_MM_yyyy = new SimpleDateFormat("dd-MM-yyyy");
DateTimeHelper helper;
/**
* set UTC Date to the calendar instance
*
* @param strDate
* date to set
*/
public static void setDate(String strDate) {
try {
Date date = (Date) formatter.parse(strDate);
cal = Calendar.getInstance();
cal.setTime(date);
updateDateTime();
}
catch (ParseException e) {
e.printStackTrace();
}
}
/**
* update date every 1 second
*/
private static void updateDateTime() {
final Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
try {
cal.add(Calendar.SECOND, 1);
handler.postDelayed(this, 1000);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
/***
* get updated date from calendar in custom date format
*
* @return date
*/
public static String getDate() {
String strDate = null;
try {
strDate = formatter.format(cal.getTime());
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return strDate;
}
}
When See the logs I found date in format:2014-0011-25 04:45:38
which is completely wrong I guess because month should be 11 instead of 0011.
But when I tried to validate this date using the below function;it says that date is valid.
public static boolean isValidDate(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
How can it be a valid date? Why I am getting date in wrong format?
This issue is very random as it is reported by only user but I am very surprised by the behavior of SimpleDateFormater and Calendar API
Please help.
Upvotes: 0
Views: 427
Reputation: 984
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try this see if it works
Upvotes: 2