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

2019-08-21 14:40发布

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"

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-21 14:57
    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

查看更多
爷的心禁止访问
3楼-- · 2019-08-21 15:10

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.

查看更多
登录 后发表回答