使用毫秒的 dateFormat 的 SimpleDateFormat 解析问题

SimpleDateFormat parsing issue for dateFormat using milliseconds

我正在迁移一些数据(在 java 中),我从几个不同的来源(使用不同的格式)提取日期字符串,我需要以一致的格式发送它们。所以我有一个方法,它接受一个字符串(以及它的来源,所以我知道要使用哪种格式)并将其转换为日期,这样我就可以从那里开始。

问题:除第一种格式外,所有格式都工作正常:返回的结果日期值与我提供的原始字符串相差 0-17 分钟!

// 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;
}

示例input/output:

我想知道这种格式是否有一些我没有理解的特别之处,但在阅读周围时没有发现任何东西。有没有人看到问题可能是什么?或者你以前见过这个?

正如其他人在评论中提到的那样,其他线程回答得很好:

事实是 SSSSSS 不作为此 class 的格式存在,它只需要 3 个数字表示毫秒。所以它被解释为这样。 DateFormat 会将 712754 解释为 712754/1000 秒而不是 0.712754 秒。 如果你做微积分,它是 11,86。分钟,这意味着 11mn52 秒。 所以33:08+11:52,就是45:00,你得到的结果。

至于解决方案,您可以去掉剩余的毫秒部分,因为无论如何您都不需要它(就像您所做的那样),或者使用另一个 class(来自 Ole 的所有评论 V.V 正点)。