Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find seconds since 1970 in java

Tags:

java

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.

like image 615
androiduser Avatar asked Nov 24 '11 22:11

androiduser


People also ask

How to get time since 1970 Java?

The getEpochSecond() method of Instant class is used to return the number of seconds from the Java epoch of 1970-01-01T00:00:00Z.

What is epoch seconds in Java?

The epoch-seconds are measured from the standard Java epoch of 1970-01-01T00:00:00Z where instants after the epoch have positive values, and earlier instants have negative values.

How do you convert string to milliseconds in Java?

Using SimpleDateFormat Calling getTime() will return the milliseconds. SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = sdf. parse(dateStr); long millis = date.


2 Answers

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; 
like image 152
makes Avatar answered Sep 22 '22 10:09

makes


Since Java8:

java.time.Instant.now().getEpochSecond() 
like image 41
singh2005 Avatar answered Sep 23 '22 10:09

singh2005