tags:

views:

1176

answers:

4

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().

+1  A: 

Take a look at the Calendar class.

You can make a Data with the current time (not deprecated) and then make Calendar from that (there are other ways too).

TofuBeer
+6  A: 

Using 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

David Sykes
Calendar actually has a getTimeInMillis() method that is a little more direct than getTime().getTime(). +1 anyway.
Outlaw Programmer
+1  A: 

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.

Daniel Schneller
+2  A: 

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.

jfpoilpret
I also recommend to look at JODA-Time - current java.util.Date and Calendar are quite broken in many ways (on JODA page there is motivational story about why JODA project was created in the first place).
Neeme Praks