简体   繁体   中英

Java Built In Date Manipulation and Comparison

I'm looking to create a datetime stamp, then add 10 hours to it, then have a thread check to see if the time has elapsed.

I read through, Time comparison but it seems a bit complicated/convoluted for something so simple. Especially if your time comparison goes across midnight.

My understanding is that java's underlying datetime, is suppose to be a long, if this is true, is there a simple way to add another long to it, such as the number equivalent of 10 hours? Or some other means such as adding two dates?

Note: The solution needs to be part of core java, can't be part of a 3rd party lib.

You can use a Calendar to perform that math,

Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, 10); // Add 10 hours.
Date date2 = cal.getTime(); // Now plus 10 hours.
Date date = new Date(); // Now.

You can use the Date.getTime() method to obtain the underlying timestamp, the timestamp is basically the number of milliseconds elapsed since a defined base instant (1970-01-01 00:00:00 IIRC).

System.currentTimeMillis() allows you the get the "now" instant directly, without any detours using Date , Calendar and the like.

The timestamp can then be manipulated basic math:

 timestamp += TimeUnit.MILLISECONDS.convert(10, TimeUnit.HOURS);

Example of adding 10 hours:

long nowInMilliSince1970 = System.currentTimeMillis();
long tenHoursAsMilli = TimeUnit.MILLISECONDS.convert(10L, TimeUnit.MINUTES);
long tenHoursLater = nowInMilliSince1970 + tenHoursAsMilli;
System.out.println("now in milliseconds: \t\t" + nowInMilliSince1970);
System.out.println("10 hours in milliseconds: \t" + tenHoursAsMilli);
System.out.println("10 hours from now: \t\t" + tenHoursLater);

Checking if the timestamp is in the past is as easy as:

 if (timestamp < System.currentTimeMillis()) {
     System.out.println("timestamp is in the past");
 }

Do note that direct timestamp math has no concept of daylight saving and time zones. If you want that, use a Calendar for math - Calendar implements the dirty exceptional rules for that.

Another way of achieving it using just JDK built in stuff is:

long tenHoursFromNow = System.currentTimeMillis() + TimeUnit.HOURS.toMillis(10);

and then in your Thread you would check:

if(System.currentTimeMillis() > tenHoursFromNow)
{
        //Do something as the time has elapsed 
}

Although I would argue that the use of Calendar and Date is clearer as to what the intention of your code is trying to achieve.

The bundled java.util.Date and .Calendar are notoriously troublesome. They really should be avoided.

You stated a requirement of no added libraries. So see the java.time part of my answer, using the new package newly added to Java 8. But I urge you to reconsider your reluctance to add a library, especially if you cannot move to Java 8 yet; juDate/Calendar really are that bad.

Both libraries handle anomalies such as Daylight Saving Time.

Consider specifying a time zone rather than rely on the JVM's default. Generally best to work in UTC , and then translate to a local time zone for presentation to the user.

java.time

The java.time package is newly added to Java 8 . Inspired by Joda-Time but re-architected. Defined by JSR 310 . Extended by the threeten-extra project.

ZonedDateTime tenHoursLater = ZonedDateTime.now().plusHours( 10 );

Joda-Time

Using the Joda-Time 2.3 library.

DateTime tenHoursLater = DateTime.now().plusHours( 10 );

For more info on this kind of use of Joda-Time, see my answer to a similar question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM