Managing Date/Time Fields in Java

As explained in the Datetime FIelds page, a field of type datetime (actually mapped to class java.util.Date) is a 64 bit integer value used to store the date and time in databases and the precision of Datetime values is determined by the runtime parameter DATETIME_PRECISION which represents the number of ticks per second. The default value for DATETIME_PRECISION is 1000, which means that the database stores a Datetime value as the number of milliseconds since the EPOCH (i.e. 00:00:00 UTC 1 January 1970).

For example , the following code snippet defines a Datetime field d and a sequence of Datetime values sd:

 
    @Persistent
    class T
    {
        Date d;
         
        @Sequence(type=Sequence.Type.DateTime)
        UnorderedSequence sd;
    };
     

The resolution of Date fields can be changed by an application via the runtime option RT_OPTION_DATETIME_PRECISION. The DATETIME_PRECISION can be set to 1 to store the number of seconds, or 1000000 (1,000,000) to store the number of microseconds. For example:

 
    Database db = new Database(config);
    db.SetRuntimeOption(Database.RT_OPTION_DATETIME_PRECISION, 1000000);
     

The following code snippet demonstrates how to store and load Date values using the Java native interface:

 
    T t = new T();
    t.d = new Date(...);
    ...
    con.insert(t)
     
    ...
     
    Cursor<T> cursor = new Cursor<T>(con, T.class, ...);
    for (T t : cursor) 
    {
        System.out.println(t.d);
    }
     

The following code snippet demonstrates how to store and load Date values using SQL:

 
    Date d = new Date(...);
    Date sd = new Date[N];
    <create sd elements>
    con.executeStatement("INSERT INTO T VALUES(?,?)", d, sd);
     
    ...
     
    SqlResultSet result = con.executeQuery("SELECT d, sd FROM T");
    for (SqlTuple tuple: result) 
    {
        Date d = (Date) tuple.get(0);
        Date[] sd = new Date[1];
        SequenceIterator seq = (SequenceIterator)tuple.get(1);
        System.out.println("d : " + d);
        while (seq.get(sd) > 0) 
        {
            System.out.println("    sd : " + sd[0]);
        }
    }
    result.close();