Since java.util.Date is mostly deprecated, what's the right way to get a timestamp for a given date, UTC time? The one that could be compared against System.currentTimeMillis()
.
views:
1176answers:
4Using the Calendar class you can create a time stamp at a specific time in a specific timezone. Once you have that, you can then get the millisecond time stamp to compare with:
Calendar cal = new GregorianCalendar();
cal.set(Calendar.DAY_OF_MONTH, 10);
// etc...
if (System.currentTimeMillis() < cal.getTimeInMillis()) {
// do your stuff
}
edit: changed to use more direct method to get time in milliseconds from Calendar instance. Thanks Outlaw Programmer
The "official" replacement for many things Date was used for is Calendar. Unfortunately it is rather clumsy and over-engineered. Your problem can be solved like this:
long currentMillis = System.currentTimeMillis();
Date date = new Date(currentMillis);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
long calendarMillis = calendar.getTimeInMillis();
assert currentMillis == calendarMillis;
Calendars can also be initialized in different ways, even one field at a time (hour, minute, second, etc.). Have a look at the Javadoc.
Although I didn't try it myself, I believe you should take a look at the JODA-Time project (open source) if your project allows external libs. AFAIK, JODA time has contributed a lot to a new JSR (normally in Java7) on date/time.
Many people claim JODA time is the solution to all java.util.Date/Calendar problems;-)
Definitely worth a try.