SimpleDateFormatter.parse提供与指定格式不同的输出 [英] SimpleDateFormatter.parse giving output in different format than specified

查看:344
本文介绍了SimpleDateFormatter.parse提供与指定格式不同的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取UNIX时间戳(字符串),将其转换为特定格式的日期,并将其存储在DATETIME列中的MySQL数据库中.

I have a requirement to fetch a UNIX timestamp (String), convert it into a date in a specific format, and store it in a MySQL DB in a DATETIME Column.

这是我的代码段(简化):

Here is my piece of code (simplified):

String ep ="a1527069600";
Long epoch = Long.parseLong(ep.substring(1, ep.length()));
Date dt = new Date(epoch*1000L);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
a");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
System.out.println("SDF.Format - "+sdf.format(dt));
System.out.println("SDF.parse - "+sdf.parse(sdf.format(dt)));

控制台输出:

SDF.Format - 23/05/2018 03:30:00 PM <br>
SDF.parse - Wed May 23 15:30:00 IST 2018

当我尝试在MySQL数据库中推送此值时,它将引发Invalid DateError.

When I try to push this value in a MySQL DB, it throws Invalid DateError.

只是困惑为什么sdf.formatsdf.parse以不同的格式显示时间戳.

Just confused why sdf.format and sdf.parse shows timestamp in different formats.

推荐答案

不要将日期作为字符串传递到MySQL数据库.传递日期对象更好,更容易,更安全.一方面,它可以减轻格式设置和任何格式设置问题.最好从现代Java日期和时间API java.time中传递类的实例.对于您来说,LocalDateTime可以.

Don’t pass dates as strings to your MySQL database. It’s better, both easier and safer to pass date objects. For one thing, it relieves you of formatting and any formatting issues. Best, pass instances of a class from java.time, the modern Java date and time API. In your case a LocalDateTime will do.

    String ep ="a1527069600";
    long epoch = Long.parseLong(ep.substring(1));
    Instant inst = Instant.ofEpochSecond(epoch);
    LocalDateTime ldt = inst.atZone(ZoneId.of("Asia/Calcutta")).toLocalDateTime();

    System.out.println(ldt);

    PreparedStatement ps = myDatabaseConnection.prepareStatement(
            "insert into my_table (my_date_time) values (?)");
    ps.setObject(1, ldt);

获得的LocalDateTime是:

2018-05-23T15:30

2018-05-23T15:30

我简化了从纪元字符串的转换.使用基本的小写long而不是Long对象.我正在使用您的时区Asia/Calcutta,假设您的数据库值在该时区中.通常的建议是将数据库值保持为UTC,至少在有可能在您所在时区之外使用数据的情况下.如果您要这样做,请使用此转换,而不要使用上面的转换:

I simplified your conversion from epoch string a bit. Use a primitive, lowercase long rather than a Long object. I am using your time zone, Asia/Calcutta, assuming that your database values are in this time zone. Normal recommendations are to keep database values in UTC, at least if there’s any possibility that the data will ever be used outside your time zone. If you want this, use this conversion instead of the one above:

    LocalDateTime ldt = inst.atOffset(ZoneOffset.UTC).toLocalDateTime();

链接: Oracle教程:日期时间解释如何使用java.time.

这篇关于SimpleDateFormatter.parse提供与指定格式不同的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆