5

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

yanchenko
  • 56,576
  • 33
  • 147
  • 165
  • Be aware: The troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), and `java.text.SimpleTextFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. – Basil Bourque Feb 06 '17 at 00:49

4 Answers4

10

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
  • 7,131
  • 4
  • 36
  • 39
  • 2
    Calendar actually has a getTimeInMillis() method that is a little more direct than getTime().getTime(). +1 anyway. – Tim Frey Mar 11 '09 at 00:53
7

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
  • 13,728
  • 5
  • 43
  • 72
3

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
  • 10,449
  • 2
  • 28
  • 32
  • 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 Mar 11 '09 at 06:45
1

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
  • 60,850
  • 18
  • 118
  • 163