I'm working on migrating some data (in java) where I'm pulling date strings from several different sources (that use different formats) and I need to send them along in a consistent format. So I have a method that takes a string (and the source it came from so I know which format to use) and converts it into a date, so I can go from there.
Problem: all of the formats work perfectly except for the first one: the resulting date values returned are between 0-17 minutes off from the original string I give it!
// Take a string, convert to a date
public static Date convertStringToDate (String dateString, String source) {
String dateFormat = null;
switch (source)
{
case "DATA": //@FIXME: these vary 0-17 minutes off!
dateFormat = "yyyy-MM-dd HH:mm:ss.SSSSSS"; // 2018-08-29 20:09:26.863631 (ex: mailing list records)
break;
case "DATA_EN": // encrypted dates use a different format
dateFormat = "yyyy-MM-dd HH:mm:ss ZZZZ"; // 2019-06-12 14:33:27 +0000 (ex: encrypted_patient_information_complete_at)
break;
case "DatStat":
dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"; // 2018-08-29T14:33:49Z (ex: followup survey)
break;
case "download":
if (dateString.length() > 10 ){ // the majority of these will be in format 1/9/16 9:30
dateFormat = "M/dd/yy HH:mm"; // 2/16/18 19:58 (ex: csv from datstat)
} else { // dates submitted at midnight lose their time and have format 9-Jan-16
dateFormat = "dd-MMM-yy"; // 9-Jan-16
}
break;
default:
dateFormat = "INVALID SOURCE VALUE GIVEN";
break;
}
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Date dt = null;
try {
dt = sdf.parse(dateString);
}
catch (Exception ex) {
throw new RuntimeException("An error has occurred trying to parse timestamp." + dateString, ex);
}
return dt;
}
Example input/output:
- String saved: "2019-06-12 14:33:08.712754"
- Date we get: "2019-06-12T14:45:00Z"
I'm wondering if there's something particular to this format that I'm not getting right, but haven't found anything in reading around. Does anyone see what the issue could be? Or have you seen this before?