Format String yyyy-mm-dd hh:mm:ss +timezone into DateTime

僤鯓⒐⒋嵵緔 提交于 2020-01-06 04:46:06

问题


I need to format a String that looks like this:

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

into a DateTime object like this:

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

My approach has been:

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

But I'm getting a parse error:

java.text.ParseException: Unparseable date: "2018-07-20 18:53:46.598000 +02:00:00"

回答1:


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);

Output from this snippet is:

20/07/2018 09:53:46

Generally you need two formatters for converting a date or date-time from one format to another: one that specifies the format to convert from and one that specifies the format to convert to.

into a DateTime object like this

A date-time object doesn’t have a format, so in that respect cannot be “like this”. dateTimeWithTimeZoneApplied in the above snippet is in the specified time zone, so has the hours adjusted. After converting to this time zone I have formatted into a string in the format you mentioned, in case you wanted this (I didn’t find it clear).

I am using and recommending java.time, the modern Java date and time API. The date and time classes you were using, Date and SimpleDateFormat, are long outdated and poorly designed, it’s not worth struggling with them. Also SimpleDateFormat supports only milliseconds so can only work correctly with exactly 3 decimals on the seconds, not with the 6 decimals you have got.

Link: Oracle tutorial: Date Time explaining how to use java.time.




回答2:


    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());

The above code will give you current Timestamp.Timestamp will provide better feasibilty



来源:https://stackoverflow.com/questions/51894572/format-string-yyyy-mm-dd-hhmmss-timezone-into-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!