2

TL;DR version: Please confirm (or if not, provide assistance) that I'm getting SQL Server datetimeoffset data into my Joda Time Java objects correctly.


I'm in the middle of planning moving our database and Java code to be time-zone-aware. To accomplish this, I have been all over this post and am attempting to implement the best practices. Note that all code is considered "throw-away" code, so I'm not really concerned with efficiency here; just correctness.

Our environment consists of a Microsoft SQL Server 2008 database and a Java service layer whereby we access all data through stored procedures and Spring SimpleJdbcCall's.

One of the best practices mentioned is to use the Joda Time library. Since this is new to me, as is the datetimeoffset SQL datatype, I'd like to ensure that I'm doing this correctly (and thus not losing any information.)

Inside SQL Server, I created a table for testing all of the various SQL Server get-time-type functions:

CREATE TABLE MIKE_TEMP (
    ID INT NOT NULL IDENTITY,
    BLAH NVARCHAR(255),

    DT_GET_DATE DATETIME DEFAULT GETDATE() NOT NULL,
    DT_GET_UTC_DATE DATETIME DEFAULT GETUTCDATE() NOT NULL,
    DT_SYS_DATE_TIME DATETIME DEFAULT sysdatetime() NOT NULL,
    DT_SYS_UTC_DATE_TIME DATETIME DEFAULT sysutcdatetime() NOT NULL,
    DT_SYS_DATE_TIME_OFFSET DATETIME DEFAULT sysdatetimeoffset() NOT NULL,

    DTO_GET_DATE DATETIMEOFFSET DEFAULT GETDATE() NOT NULL,
    DTO_GET_UTC_DATE DATETIMEOFFSET DEFAULT GETUTCDATE() NOT NULL,
    DTO_SYS_DATE_TIME DATETIMEOFFSET DEFAULT sysdatetime() NOT NULL,
    DTO_SYS_UTC_DATE_TIME DATETIMEOFFSET DEFAULT sysutcdatetime() NOT NULL,
    DTO_SYS_DATE_TIME_OFFSET DATETIMEOFFSET DEFAULT sysdatetimeoffset() NOT NULL
);

Into this table, I added one value, blah = 'Hello World!'. The resulting data is:

ID BLAH         DT_GET_DATE         DT_GET_UTC_DATE     DT_SYS_DATE_TIME    DT_SYS_UTC_DATE_TIME DT_SYS_DATE_TIME_OFFSET DTO_GET_DATE                       DTO_GET_UTC_DATE                   DTO_SYS_DATE_TIME                  DTO_SYS_UTC_DATE_TIME              DTO_SYS_DATE_TIME_OFFSET           
-- ------------ ------------------- ------------------- ------------------- -------------------- ----------------------- ---------------------------------- ---------------------------------- ---------------------------------- ---------------------------------- ---------------------------------- 
1  Hello World! 2012-02-15 08:58:41 2012-02-15 14:58:41 2012-02-15 08:58:41 2012-02-15 14:58:41  2012-02-15 08:58:41     2012-02-15 08:58:41.6000000 +00:00 2012-02-15 14:58:41.6000000 +00:00 2012-02-15 08:58:41.6005458 +00:00 2012-02-15 14:58:41.6005458 +00:00 2012-02-15 08:58:41.6005458 -06:00 

There is a corresponding stored procedure that simply does a select * from MIKE_TEMP and returns all data as output parameters.

The Java code that accesses this data is (only "interesting" imports included for clarity):

import org.joda.time.DateTime;
import java.util.Date;

@Component
public class MikeTempDaoImpl {
    private static final Logger logger = LoggerFactory.getLogger(MikeTempDaoImpl.class);

    private DataSource dataSource;

    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public MikeVTemp getMikeTemp() {
        SimpleJdbcCall data = new SimpleJdbcCall(getDataSource());

        data.withProcedureName("get_MIKE_TEMP");
        data.withoutProcedureColumnMetaDataAccess();
        data.declareParameters(
                new SqlOutParameter("ID", Types.INTEGER),
                new SqlOutParameter("BLAH", Types.NVARCHAR),
                new SqlOutParameter("DT_GET_DATE", Types.TIMESTAMP),
                new SqlOutParameter("DT_GET_UTC_DATE", Types.TIMESTAMP),
                new SqlOutParameter("DT_SYS_DATE_TIME", Types.TIMESTAMP),
                new SqlOutParameter("DT_SYS_UTC_DATE_TIME", Types.TIMESTAMP),
                new SqlOutParameter("DT_SYS_DATE_TIME_OFFSET", Types.TIMESTAMP),
                new SqlOutParameter("DTO_GET_DATE", Types.TIMESTAMP),
                new SqlOutParameter("DTO_GET_UTC_DATE", Types.TIMESTAMP),
                new SqlOutParameter("DTO_SYS_DATE_TIME", Types.TIMESTAMP),
                new SqlOutParameter("DTO_SYS_UTC_DATE_TIME", Types.TIMESTAMP),
                new SqlOutParameter("DTO_SYS_DATE_TIME_OFFSET", Types.TIMESTAMP)
        );

        Map out;

        try {
            out = data.execute();
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }

        int id = (Integer) out.get("ID");
        String blah = (String) out.get("BLAH");
        DateTime dtGetDate = new DateTime((Date) out.get("DT_GET_DATE"));
        DateTime dtGetUtcDate = new DateTime((Date) out.get("DT_GET_UTC_DATE"));
        DateTime dtSysDateTime = new DateTime((Date) out.get("DT_SYS_DATE_TIME"));
        DateTime dtSysUtcDateTime = new DateTime((Date) out.get("DT_SYS_UTC_DATE_TIME"));
        DateTime dtSysDateTimeOffset = new DateTime((Date) out.get("DT_SYS_DATE_TIME_OFFSET"));
        DateTime dtoGetDate = new DateTime((Date) out.get("DTO_GET_DATE"));
        DateTime dtoGetUtcDate = new DateTime((Date) out.get("DTO_GET_UTC_DATE"));
        DateTime dtoSysDateTime = new DateTime((Date) out.get("DTO_SYS_DATE_TIME"));
        DateTime dtoSysUtcDateTime = new DateTime((Date) out.get("DTO_SYS_UTC_DATE_TIME"));
        DateTime dtoSysDateTimeOffset = new DateTime((Date) out.get("DTO_SYS_DATE_TIME_OFFSET"));

        MikeTemp mt = new MikeTemp.Builder()
                .id(id)
                .blah(blah)
                .dtGetDate(dtGetDate)
                .dtGetUtcDate(dtGetUtcDate)
                .dtSysDateTime(dtSysDateTime)
                .dtSysUtcDateTime(dtSysUtcDateTime)
                .dtSysDateTimeOffset(dtSysDateTimeOffset)
                .dtoGetDate(dtoGetDate)
                .dtoGetUtcDate(dtoGetUtcDate)
                .dtoSysDateTime(dtoSysDateTime)
                .dtoSysUtcDateTime(dtoSysUtcDateTime)
                .dtoSysDateTimeOffset(dtoSysDateTimeOffset)
                .build();

        System.out.println("id                   = [" + mt.getId() + "]");
        System.out.println("blah                 = [" + mt.getBlah() + "]");
        System.out.println("dtGetDate            = [" + mt.getDtGetDate() + "]");
        System.out.println("dtGetUtcDate         = [" + mt.getDtGetUtcDate() + "]");
        System.out.println("dtSysDateTime        = [" + mt.getDtSysDateTime() + "]");
        System.out.println("dtSysUtcDateTime     = [" + mt.getDtSysUtcDateTime() + "]");
        System.out.println("dtSysDateTimeOffset  = [" + mt.getDtSysDateTimeOffset() + "]");
        System.out.println("dtoGetDate           = [" + mt.getDtoGetDate() + "]");
        System.out.println("dtoGetUtcDate        = [" + mt.getDtoGetUtcDate() + "]");
        System.out.println("dtoSysDateTime       = [" + mt.getDtoSysDateTime() + "]");
        System.out.println("dtoSysUtcDateTime    = [" + mt.getDtoSysUtcDateTime() + "]");
        System.out.println("dtoSysDateTimeOffset = [" + mt.getDtoSysDateTimeOffset() + "]");

        return mvt;
    }
}

This is being exercised by a JUnit test:

@Test
public void testDateData() throws Exception {
    MikeTemp mt = dao.getMikeTemp();

    assertNotNull("MT should not be null, but it is.", mt);
    assertEquals(1, mt.getId());
    assertEquals("Hello World!", mt.getBlah());
}

And the results from all of the println's are:

id                   = [1]
blah                 = [Hello World!]
dtGetDate            = [2012-02-15T08:58:41.577-06:00]
dtGetUtcDate         = [2012-02-15T14:58:41.577-06:00]
dtSysDateTime        = [2012-02-15T08:58:41.580-06:00]
dtSysUtcDateTime     = [2012-02-15T14:58:41.600-06:00]
dtSysDateTimeOffset  = [2012-02-15T08:58:41.600-06:00]
dtoGetDate           = [2012-02-15T08:58:41.600-06:00]
dtoGetUtcDate        = [2012-02-15T14:58:41.600-06:00]
dtoSysDateTime       = [2012-02-15T08:58:41.600-06:00]
dtoSysUtcDateTime    = [2012-02-15T14:58:41.600-06:00]
dtoSysDateTimeOffset = [2012-02-15T08:58:41.600-06:00]

Being as this server is in the US Central Time Zone, I definitely expect to see -06:00 for some of the results, but rather definitely not all of them. Have I missed something somewhere along the way? Is calling the Joda DateTime(Object) ctor with a java.util.Date object the correct thing to do in this situation? What else could/should I be doing that I'm not?

Thanks!

Community
  • 1
  • 1
Mike
  • 7,994
  • 5
  • 35
  • 44
  • 1
    Your key problem is that the `java.util.Date` does not store custom timezone information. It's always UTC. This code is too much abstracted away from raw JDBC in order to give a suitable answer, but to the point you likely need the `ResultSet#getTimestamp()` method wherein you pass a `java.util.Calendar` which holds the timezone. – BalusC Feb 20 '12 at 03:02

2 Answers2

2

No, this isn't the way to do it. You're using the DateTime(Object) constructor with a Date which only knows about an instant in time, and uses the system default time zone.

As BalusC wrote, you could pass a Calendar into ResultSet.getTimestamp() if you want to specify the time zone yourself - but that's not the same as preserving the information that's already present in the database.

It's not clear which JDBC driver you're using, and you'd probably have to move away from SimpleJdbcCall, but the Microsoft JDBC driver v3.0 has SQLServerCallableStatement.getDateTimeOffset (and ditto for SQLServerResultSet) which would presumably do the right thing. Given that your data type isn't really portable, it means your code can't really be either :(

Do you definitely need to preserve the offset? If not, you could probably concentrate on getting the right instant out using the "normal" JDBC calls - which unfortunately it looks like it's not doing at the moment.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks for the pointer to the MSJDBC 3.0 driver. We're currently using 2.0 of the same driver, but it appears that updating versions will provide us the ability to natively support the `datetimeoffset` data type in our Java code with no loss of information from the database side. Reasonably sure this is awfully close to what we're looking for. Thanks again! – Mike Feb 24 '12 at 16:15
1

If you want to avoid java.util.Date/Calendar completely, this is what I've done

SQL server side:

SELECT CONVERT(NVARCHAR, DateFieldName, 126) AS DateFieldIsoString

where DateFieldName is a datetimeoffset field, and the query returns a java.lang.String

Parsing the String into a Joda DateTime:

DateTime datetime = ISODateTimeFormat.dateTimeParser().withOffsetParsed()
          .parse(dateFieldAsString)
artbristol
  • 32,010
  • 5
  • 70
  • 103