Search code examples
javadatetimetimezonetalend

Talend: Timezone java


I am trying to learn Talend Open Studio. I have a column with strings like "2019-09-17 08:42:09 +0400" and I want to convert this with java components and not with tmap to a datetime but with the "+0400" added to my time. I tried a lot of things like LocalDate but it didn't work.

Please if anyone knows how to do it I will appreciate it.Thanks a lot.


Solution

  • java.time

        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .append(DateTimeFormatter.ISO_LOCAL_DATE)
                .appendLiteral(' ')
                .append(DateTimeFormatter.ISO_LOCAL_TIME)
                .appendLiteral(' ')
                .appendOffset("+HHmm", "+0000")
                .toFormatter();
    
        String stringFromTalendCol = "2019-09-17 08:42:09 +0400";
    
        OffsetDateTime javaDateTime = OffsetDateTime.parse(stringFromTalendCol, formatter);
    
        System.out.println(javaDateTime);
    

    The output from this snippet is:

    2019-09-17T08:42:09+04:00

    If you’re into brevity of code, the formatter may alternatively be defined in just one line:

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss xx");
    

    My taste is for reusing the building blocks that java.time offers, which is why I presented the longer option first. The result is the same in both cases.

    LocalDate is not enough

    You mentioned that you tried LocalDate. A LocalDate is a date without time of day and without time zone or offset from UTC, so it cannot represent the date and time from your question, which may be one reason why your attempts didn’t work.

    Your string has a date, a time of day and a UTC offset. OffsetDateTime is the exactly correct class for representing this information.

    The offset of +0400 means that an offset of 4 hours 0 minutes has been added to the time compared to UTC. So your point in time is equivalent to 2019-09-17T04:42:09Z, where Z denotes UTC or offset zero.

    Link

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