What is the correct format to use with joda time datetime formatter in Mirth?

Viewed 700

In one of the HL7 date time values, I get values like 202009010935-0400 I am trying to use joda time to parse that and convert into a yyyy-MM-dd'T'HH:mm:ss format. Using this line of code

var instant = org.joda.time.format.DateTimeFormat.forPattern('yyyyMMddHHmm-ZZZZ').parseMillis(new String(date));
var value = org.joda.time.format.DateTimeFormat.forPattern(yyyy-MM-dd'T'HH:mm:ss).print(instant);

throws an exception

JavaException: java.lang.IllegalArgumentException: Invalid format: "202009010935-0400" is malformed at "-0400"

Since I have no control over the data value sent, what's the correct format to use in this case?

I have tried using yyyyMMddHHmm-HHmm but that simply converts the date to 2020-09-01T04:00

1 Answers

You should use the pattern, yyyyMMddHHmmZ and do as follows:

Demo:

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String dateTimeStr = "202009010935-0400";
        DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyyMMddHHmmZ").withOffsetParsed();
        DateTime dateTime = dtf.parseDateTime(dateTimeStr);
        System.out.println(dateTime);    
    }
}

Output:

2020-09-01T09:35:00.000-04:00

Check DateTimeFormat to learn more about the patterns.

Note: Check the following notice at the Home Page of Joda-Time

Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).

Using the java.time (JSR-301) API:

import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String dateTimeStr = "202009010935-0400";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMMddHHmmZ");
        OffsetDateTime odt = OffsetDateTime.parse(dateTimeStr, dtf);
        System.out.println(odt);
    }
}

Output:

2020-09-01T09:35-04:00

Learn about the modern date-time API from Trail: Date Time.

Related