Reputation: 13
I'm facing a strange problem using SimpleDateFormat
method in Android. Sometimes (very rarely) format
method return a bad formatted date. Here is the code and below the output. Can you explain me the cause of that 0s?
Here is the code:
public class MyObject{
protected Timestamp detectionDate;
public String getDetectionDateAsString() {
String dateAsString = Constant.ISO_8601_TS_DF.format(detectionDate);
if(dateAsString.length()>19){
logger.warn("ERROR ON FORMAT DATE");
logger.warn("dateAsString:" + dateAsString);
logger.warn("detectionDate:" + detectionDate);
}
}
}
public class Constant {
public static final SimpleDateFormat ISO_8601_TS_DF =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
Output:
14:35:05.150 [AsyncTask #2] WARN i.m.t.d.o.OutcomesTableData - ERROR ON FORMAT DATE
14:35:05.150 [AsyncTask #2] WARN i.m.t.d.o.OutcomesTableData - dateAsString:2016-0007-0001 0000:00:0000
14:35:05.151 [AsyncTask #2] WARN i.m.t.d.o.OutcomesTableData - detectionDate:2016-07-03 12:34:27.194
Thank you
Upvotes: 1
Views: 54
Reputation: 20258
The TimeStamp
class already returns a string in specified format (look at the field TIME_FORMAT_REGEX
in TimeStamp
class), so invoking toString()
method will return you the string in format you wish.
Upvotes: 0
Reputation: 5149
Whilst Timestamp
is an extension of Date
according to the docs:
The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance.
To fix your issue, you could try using Calendar
instead:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp.getTime());
String format = dateFormat.format(cal.getTime());
Upvotes: 2