Unix epoch time from Java Date object

JavaIO

What is epoch time?

The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z). Literally speaking the epoch is Unix time 0 (midnight 1/1/1970), but ‘epoch’ is often used as a synonym for ‘Unix time’. Many Unix systems store epoch dates as a signed 32-bit integer, which might cause problems on January 19, 2038 (known as the Year 2038 problem or Y2038).

1. Convert Current Date to epoch Time

We need to first create a java.util.Date object ad from that get the time using getTime() and divide the output by 1000. This will give the unix epoch time.

package com.jkoder;

import java.util.Date;

public class DateToEpoch {
	public static void main(String[] args) {
		Date currentDate = new Date();
		long epochstring = currentDate.getTime() / 1000;
		System.out.println(epochstring);
	}
}

2. Convert a Date to epoch Time for a Timezone

We need to first specify a timezone and then will parse the date string using java.text.SimpleDateFormat to convert the date string to java.util.Date object then get the time using getTime() and divide the output by 1000. This will give the unix epoch time.

package com.jkoder;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

public class DateToEpoch {

	public static void main(String[] args) {
		long epochstring = toEpochTime("2014-05-14 12:59");
		System.out.println(epochstring);
	}
	public static long toEpochTime(String time) {
		DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		long epochstring = 0;
		
		// Specify your timezone
		dateformat.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
		try {
			epochstring = dateformat.parse(time).getTime();
			epochstring = epochstring / 1000;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return epochstring;
	}

}