user3712321 user3712321 - 1 year ago 123
Java Question

Use different date as UNIX epoch time in Java?

I know that the standard UNIX epoch time is 1/1/70 and I can use this variable to convert current time to UNIX time:

int time = (int) ((System.currentTimeMillis())/1000);

(Note: I know it's normally stored as a 64-bit long but I need it to be 32 bit, hence the cast to int).

My question is - are there any built-in methods in Java where you can pass in a different date as the "epoch date." What I am trying to get is a timestamp in # of seconds since a particular date. I.e. I would like to define January 1, 2015 as MY epoch. And then each future date would be # of seconds since 1/1/2015.

If there's no Java library that provides that capability, any ideas on how to do this?

Answer Source

There is no library needed, you just have to use maths.

static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
static final long EPOCH = new Date(2015 - 1900, Calendar.JANUARY, 1).getTime(); // 2015/1/1 in GMT

public static int secondSinceEpoch() {
    return (int) ((System.currentTimeMillis() - EPOCH) / 1000);

public static String epochToString(int secsSince2015) {
    return SDF.format(new Date(secsSince2015 * 1000 + EPOCH));

public static void main(String... ignored) {
    System.out.println(new Date(EPOCH));
    System.out.println("Epoch is " + epochToString(0));
    System.out.println("Today is " + secondSinceEpoch() + " secs");
    System.out.println("Today is " + secondSinceEpoch() / 86400 + " days");


Thu Jan 01 00:00:00 GMT 2015
Epoch is 2015/01/01 00:00:00
Today is -15732850 secs
Today is -182 days
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download