Converts a Macintosh-style timestamp (seconds since January 1, 1904) into a Java date. - Java java.sql

Java examples for java.sql:Timestamp

Description

Converts a Macintosh-style timestamp (seconds since January 1, 1904) into a Java date.

Demo Code


//package com.java2s;

import java.util.Calendar;
import java.util.Date;

public class Main {
    public static void main(String[] argv) throws Exception {
        long timestamp = 2;
        System.out.println(timestampToDate(timestamp));
    }/*  w  w w.ja v a2  s  . c  o  m*/

    /** Converts a Macintosh-style timestamp (seconds since
     *  January 1, 1904) into a Java date.  The timestamp is
     *  treated as a time in the default localization.
     *  Depending on that localization,
     *  there may be some variation in the exact hour of the date 
     *  returned, e.g., due to daylight savings time.
     * 
     */
    public static Date timestampToDate(long timestamp) {
        Calendar cal = Calendar.getInstance();
        cal.set(1904, 0, 1, 0, 0, 0);

        // If we add the seconds directly, we'll truncate the long
        // value when converting to int.  So convert to hours plus
        // residual seconds.
        int hours = (int) (timestamp / 3600);
        int seconds = (int) (timestamp - (long) hours * 3600L);
        cal.add(Calendar.HOUR_OF_DAY, hours);
        cal.add(Calendar.SECOND, seconds);
        Date dat = cal.getTime();
        return dat;
    }
}

Related Tutorials