how to find seconds since 1970 in java
The methods Calendar.getTimeInMillis()
and Date.getTime()
both return milliseconds since 1.1.1970.
For current time, you can use:
long seconds = System.currentTimeMillis() / 1000l;
Since Java8:
java.time.Instant.now().getEpochSecond()
Based on your desire that 1317427200
be the output, there are several layers of issue to address.
First as others have mentioned, java already uses a UTC 1/1/1970 epoch. There is normally no need to calculate the epoch and perform subtraction unless you have weird locale rules.
Second, when you create a new Calendar it's initialized to 'now' so it includes the time of day. Changing the year/month/day doesn't affect the time of day fields. So if you want it to represent midnight of the date, you need to zero out the calendar before you set the date.
Third, you haven't specified how you're supposed to handle time zones. Daylight Savings can cause differences in the absolute number of seconds represented by a particular calendar-on-the-wall-date, depending on where your JVM is running. Since epoch is in UTC, we probably want to work in UTC times? You may need to seek clarification from the makers of the system you're interfacing with.
Fourth, months in Java are zero indexed. January is 0, October is 9.
Putting all that together
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
calendar.set(2011, Calendar.OCTOBER, 1);
long secondsSinceEpoch = calendar.getTimeInMillis() / 1000L;
that will give you 1317427200