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.
The getEpochSecond() method of Instant class is used to return the number of seconds from the Java epoch of 1970-01-01T00:00:00Z.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With