49

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.

public long returnSeconds(int year, int month, int date) {
    Calendar calendar1 = Calendar.getInstance();
    Calendar calendar2 = Calendar.getInstance();
    calendar1.set(1970, 01, 01);
    calendar2.set(year, month, date);
    long milliseconds1 = calendar1.getTimeInMillis();
    long milliseconds2 = calendar2.getTimeInMillis();
    long diff = milliseconds2 - milliseconds1;
    long seconds = diff / 1000;
    return seconds;
}

In the above in place of year,month,date I'm passing 2011,10,1 and iam getting

1317510000

but the correct answer is

1317427200

Any help regarding this is very useful to me.

Philipp Reichart
  • 20,771
  • 6
  • 58
  • 65
androiduser
  • 917
  • 3
  • 11
  • 15
  • 3
    `getTimeInMillis()` *already* measures from the Unix epoch (1970 etc etc). If you look at milliseconds1 it should be zero (unless you're getting timezone problems). So taking the difference is unnecessary – Mark Peters Nov 24 '11 at 22:46

8 Answers8

73

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;
CoasterChris
  • 91
  • 1
  • 10
makes
  • 6,438
  • 3
  • 40
  • 58
70

Since Java8:

java.time.Instant.now().getEpochSecond()
Julien Lafont
  • 7,869
  • 2
  • 32
  • 52
singh2005
  • 1,251
  • 12
  • 19
47

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

Affe
  • 47,174
  • 11
  • 83
  • 83
  • 1
    my date and time is "19 Sep 2062 02:30:00" and i want to get "-2147483648" but i don't get. My current result is "2925858600". –  Apr 19 '13 at 05:45
  • 2
    @Varun Patel For a negative number one expects the date would be in 1962, not 2062..... – Affe Apr 19 '13 at 06:03
12

It's Date.getTime().

expert
  • 29,290
  • 30
  • 110
  • 214
5

The difference you see is most likely because you don't zero the hour, minute, second and milliseconds fields of your Calendar instances: Calendar.getInstance() gives you the current date and time, just like new Date() or System.currentTimeMillis().

Note that the month field of Calendar is zero-based, i.e. January is 0, not 1.

Also, don't prefix numbers with zero, this might look nice and it even works till you reach 8: 08 isn't a valid numeral in Java. Prefixing numerals with zero makes the compiler assume you're defining them as octal numerals which only works up to 07 (for single digits).

Just drop calendar1 completely (1970-01-01 00:00:00'000 is the begin of the epoch, i.e. zero anyway) and do this:

public long returnSeconds(int year, int month, int date) {
    final Calendar cal = Calendar.getInstance();
    cal.set(year, month, date, 0, 0, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTimeInMillis() / 1000;
}
Philipp Reichart
  • 20,771
  • 6
  • 58
  • 65
  • This looks the only complete answer to the problem.. wondering why no one noticed it. Correct implementation, same method signature as requested. – PaoloC Feb 16 '18 at 22:17
4

java.time

Using the java.time framework built into Java 8 and later.

import java.time.LocalDate;
import java.time.ZoneId;

int year = 2011;
int month = 10;
int day = 1;
int date = LocalDate.of(year, month, day);

date.atStartOfDay(ZoneId.of("UTC")).toEpochSecond; # Long = 1317427200
Przemek
  • 7,111
  • 3
  • 43
  • 52
4

The answer you want, "1317427200", is achieved if your reference months are January and October. If so, the dates you are looking for are 1970-JAN-01 and 2011-OCT-01, correct?

Then the problem are these numbers you are using for your months.

See, if you check the Calendar API documentation or even the constants provided in there ("Calendar.JANUARY", "Calendar.FEBRUARY" and so on), you'll discover that months start at 0 (being January).

So checking your code, you are passing february and november, which would result in "1317510000".

Best regards.

ThiagoUriel
  • 115
  • 6
  • oh.. iam treating january as 1 that is why i got wrong answer, any way i got the answer.You are correct.Thanks for the answer. – androiduser Nov 24 '11 at 23:19
0

Another option is to use the TimeUtils utility method:

TimeUtils.millisToUnit(System.currentTimeMillis(), TimeUnit.SECONDS)