18

I am using an API which requires a date parameter as a number of seconds, an int.

My problem is that I currently store this time in java.util.date and I was wondering if there is some way to convert the java.util.date variable to seconds so that I can fit it into the int parameter which the API requires?

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
Sam
  • 861
  • 3
  • 10
  • 16
  • 2
    Out of curiosity, does the API require any number of seconds? Or seconds from a particular epoch? Because if it will accept and work with any int of seconds, just take the seconds value from your date variable. – Nathaniel Ford Jun 19 '12 at 17:53
  • 4
    the `getTime()` methods returns the milliseconds since Epoch. Divide by 1000 to have seconds. – Denys Séguret Jun 19 '12 at 17:55
  • check [getTime](http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#getTime()) mehod in util.Date class. – Subhrajyoti Majumder Jun 19 '12 at 17:55
  • 2
    I don't understand the downvotes & flags here. It's a completely readable, on-topic question, with a concrete answer! – Richard J. Ross III Jun 20 '12 at 11:49

4 Answers4

20

import java.util.Date;

... long secs = (new Date().getTime())/1000; ...

Please see - http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#getTime()

6

Since Java 8 and onwards there's this elegant method which returns the Epoch time in seconds (seconds since 0:00:0 January 1st 1970). You can then store this value as an numeric value: a "long" in this case.

long timestamp = java.time.Instant.now().getEpochSecond();

Bigger
  • 1,807
  • 3
  • 18
  • 28
5

java.util.Date.getTime() it returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

    java.util.Date date=new Date();    
    System.out.println(date.getTime());

Output: 1340128712111

To get seconds from milliseconds you need to divide it by 1000.

long secs = date.getTime()/1000;
System.out.println(secs);

Output: 1340128712

Alternatively Instant.getEpochSecond() returns the number of seconds from the Java epoch of 1970-01-01T00:00:00Z. Its available since Java v1.8 docs.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
1

Number of seconds by itself doesn't mean much. Number of seconds within the current minute? Number of seconds since 0:00:00 Janurary 1st, 1970? Number of seconds since lunch? Could you be more specific.

Put it into the API also doesn't mean much, unless you specify exactly which API you are using, and where you are attempting to put these seconds.

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138