将字符串yyyy-mm-dd hh:mm:ss + timezone格式化为DateTime

时间:2018-08-17 11:35:33

标签: java datetime parsing timezone

我需要格式化一个看起来像这样的字符串:

-dontnote javax.annotation.*

插入到这样的DateTime对象中:

"2018-07-20 18:53:46.598000 +02:00:00" 

我的方法是:

20/07/2018 (HH with Timezone applied):53:46

但是我遇到了解析错误:

String dateTimePattern = "dd/MM/yyyy HH:mm:ss";
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(dateTimePattern);                                                                                                                                                         
Date feUltModDateTime = dateTimeFormat.parse(feUltMod);
feUltMod = feUltModDateTime.toString();

2 个答案:

答案 0 :(得分:2)

java.time

    DateTimeFormatter origFormatter 
            = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSSSSS XXXXX");
    DateTimeFormatter desiredFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu HH:mm:ss");
    ZoneId desiredZone = ZoneId.of("America/Fort_Nelson");

    String feUltMod = "2018-07-20 18:53:46.598000 +02:00:00";
    OffsetDateTime dateTime = OffsetDateTime.parse(feUltMod, origFormatter);
    ZonedDateTime dateTimeWithTimeZoneApplied = dateTime.atZoneSameInstant(desiredZone);
    feUltMod = dateTimeWithTimeZoneApplied.format(desiredFormatter);
    System.out.println(feUltMod);

此代码段的输出为:

  

20/07/2018 09:53:46

通常,您需要两个格式化程序才能将日期或日期时间从一种格式转换为另一种格式:一种指定将转换为的格式,另一种指定将转换为<< / em>。

  

插入这样的DateTime对象

日期时间对象没有格式,因此在这方面不能“像这样”。上段中的dateTimeWithTimeZoneApplied在指定的时区中,因此调整了小时数。转换到该时区后,我已经按照您提到的格式将其格式化为字符串,以防万一您想要这样做(我不清楚)。

我正在使用并推荐使用Java.time(现代Java日期和时间API)。您使用的日期和时间类别DateSimpleDateFormat早已过时且设计不当,因此不值得与之抗争。此外,SimpleDateFormat仅支持毫秒,因此只能在秒上精确到3个小数,而不是6个小数才能正常工作。

链接: Oracle tutorial: Date Time解释了如何使用java.time

答案 1 :(得分:0)

    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    Date df = new Date();
    String yourString = sdf.format(df);

    Date parsedDate = sdf.parse(yourString);
    Timestamp sqlDate = new java.sql.Timestamp(parsedDate.getTime());

上面的代码将为您提供当前的时间戳,时间戳将提供更好的可行性