ba.hons said:
wondering if someone could help i need to do a kind of date diff
operation so i can calculate how long an object should last for.
Ok. Though it's kind of a strange way to do things. This is for some sort of
cache, I presume. Normally, you want to keep caches for a fixed duration (10
minutes from last update), or in some sort of least-recently-used system based
on total cache size.
If you want to clear it all at midnight, it's probably easier to just drop the
whole cache at midnight rather than having each object calculate when midnight
is going to come.
My problem is that as am using this kind of code:
Date Edate = sdf.parse(ExpiryDate);
diff = Edate.getTime()-currentDate.getTime();
diff=diff/1000;
and i want my object to expire exactly at midnight, not at when the
currentime is taken.
Huh? Do you want to expire at a given expiryDate, or at midnight? You
haven't described enough of the problem for me to guess what data you have,
and what data you want.
If you're looking for "milliseconds until midnight in the VM default
timezone", try something on the order of:
// CAVEAT: untested code, expect typos and dumb mistakes.
Calendar midnight = Calendar.getInstance();
// roll back a day if it's midnight exactly already, so next midnight is now.
midnight.add(Calendar.MILLISECOND, -1);
// set small fields to 0
midnight.set(Calendar.MILLISECOND, 0);
midnight.set(Calendar.SECOND, 0);
midnight.set(Calendar.MINUTE, 0);
midnight.set(Calendar.HOUR_OF_DAY, 0);
// add a day.
midnight.add(Calendar.DAY_OF_MONTH, 1);
// millis from now until midnight:
long millisUntilMidnight =
midnight.getTimeInMillis() - System.currentTimeMillis();
Adjust as needed to deal with your own definitions, timezone requirements,
or with parsing dates from other sources. Say what you will about the
overcomplexification of the Calendar object, it handles things like this
reasonably well, and if you try to do it yourself, you're going to get it
wrong most of the time, when you have to track daylight/summer time, leap
years, etc.