All Things Techie With Huge, Unstructured, Intuitive Leaps

Java - How to calculate and find out how many seconds to an event in the future

Java lesson.  Let's suppose that you have an event happening in the future.  The date and time of that event is stored in a database and you want to calculate how many seconds there are to that event. Once you get seconds, you can divide by 60 to get minutes, and again by 60 to get hours and then by 24 to get days etc.

Here is a code snippet that lets you do that:

Date now = new Date();
Timestamp eventStart = rs.getTimestamp("eventStart");
GregorianCalendar gc = new GregorianCalendar();
Date endInterval = gc.getTime();
long difference = Math.abs(endInterval.getTime() - now.getTime());
long secondsToEvent = difference / (1000);

Date is java.util.Date. Timestamp is java.sql.Timestamp.

Hope this helps someone.

No comments:

Post a Comment