Skip to main content

APIzation: Replication Package

[Q#8263148][A#8263301] how to find seconds since 1970 in java

https://stackoverflow.com/q/8263148

iam working with a real time project where i got a requirement to find seconds since 1970 january 1.I have used the following code to find out seconds but is giving wrong result.The code is as follows. In the above in place of year,month,date I'm passing 2011,10,1 and iam getting but the correct answer is Any help regarding this is very useful to me.

Answer

https://stackoverflow.com/a/8263301

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 that will give you 1317427200

APIzation

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
calendar.set(2011, Calendar.OCTOBER, 1);
long secondsSinceEpoch = calendar.getTimeInMillis() / 1000L;
package com.stackoverflow.api;

import java.util.Calendar;
import java.util.TimeZone;

public class Human8263301 {

  public static long secondsSinceEpoch(
    String timeZone,
    int year,
    int month,
    int date
  ) {
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(timeZone));
    calendar.clear();
    calendar.set(year, month, date);
    return calendar.getTimeInMillis() / 1000L;
  }
}

package com.stackoverflow.api;

import java.util.Calendar;
import java.util.TimeZone;

/**
 * how to find seconds since 1970 in java
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/8263301">https://stackoverflow.com/a/8263301</a>
 */
public class APIzator8263301 {

  public static long findSecond() throws Exception {
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    calendar.clear();
    calendar.set(2011, Calendar.OCTOBER, 1);
    return calendar.getTimeInMillis() / 1000L;
  }
}