java到mysql.我需要从字符串参数转换为时间戳

我正在尝试将字符串解析为时间戳,因为我需要将此数据保存在 bbdd mysql 上.

I'm trying to parser String to Timestamp because I need to save this data on bbdd mysql.

String dateString: "2018-10-17T22:37:10.000+0000";
java.sql.Timestamp timeStampDate = null;
try {
        DateFormat formatter;
        formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
        Date date = (Date) formatter.parse(dateString);
        timeStampDate = new Timestamp(date.getTime());

    } catch (ParseException e) {
        log.debug("ERROR parser String to Timestamp to save bbdd. ", e.getMessage());
    }

当我运行我的应用程序时,我会收到以下捕获消息:

When I run my app I get this catch message:

ERROR 解析器字符串到时间戳以保存 bbdd.无法解析的日期:2018-10-17T22:37:10.000+0000"

ERROR parser String to Timestamp to save bbdd. Unparseable date: "2018-10-17T22:37:10.000+0000"

谁能帮帮我?

推荐答案

把你的掩码改成

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");

所以你有

java.sql.Timestamp timeStampDate = null;
String dateString = "2018-10-17T22:37:10.000+0000";

try {
    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    Date date = formatter.parse(dateString);
    timeStampDate = new Timestamp(date.getTime());

} catch (ParseException e) {
    e.printStackTrace();
}

顺便说一下你应该不需要cast Date

抱歉为我的懈怠,我匆忙中没有测试输出,根据@andreas 评论,正确的掩码实际上是 yyyy-MM-dd'T'HH:mm:ss.SSSZ

Apologies for my slackness, in my haste I did not test the output and as per @andreas comment, the correct mask is actually yyyy-MM-dd'T'HH:mm:ss.SSSZ

相关文章