Using GregorianCalendar.setGregorianChange for calculating time difference - java

I'm reading Uncle Bob's "The Craftsman" series, and have gotten to #29 (PDF). In it, there's this snippet in test code, for asserting dates are close enough:
private boolean DatesAreVeryClose(Date date1, Date date2) {
GregorianCalendar c1 = new GregorianCalendar();
GregorianCalendar c2 = new GregorianCalendar();
c1.setGregorianChange(date1);
c2.setGregorianChange(date2);
long differenceInMS = c1.getTimeInMillis() - c2.getTimeInMillis();
return Math.abs(differenceInMS) <= 1;
}
I read the docs, and yet couldn't figure why simply using Date.getTime() isn't good enough instead of introducing the calendar etc. Am I missing some corner cases?

Time on the spaceship is different from time in our world. Also, the java API on the spaceship is slightly different from the API in our world. The method setGrogorianChange has nothing to do with julian dates in the spaceship world. Rather it is a way to set the time of the GregorianCalendar instance. And in the spaceship world, Date.getTime() does not return milliseconds. It returns a hashed value that somehow represents the time, but cannot be subtracted or added.
So there.

I'm going to bite: that code is utter rubbish. If the use of setGregorianChange() has any purpose at all (which I doubt), it is the kind of clever hack that has no business anywhere near real world code. But I strongly suspect that whoever wrote that cutesy story just didn't know the Date/Calendar API very well and really meant to use Calendar.setTime().
The case against directly comparing Date instances in assertEquals() seems to be that the instances' internal timestamps may differ by milliseconds, even if created right after on another - thus the introduction of a "fuzzy compare" in the form of Math.abs(differenceInMS) <= 1. But neither does that require the detour via GregorianCalendar, nor is it enough fuzz - a full GC or even just the clock granularity could easily lead to two dates created right after another being 10 or more ms apart.
The real problem is the lack of a "calendar date" datatype in Java - making comparisons with day granularity pretty verbose (you have to use a Calendar to set all time fields to 0). Joda Time's DateMidnight class is what is really needed here.

There is no good reason not to use Date.getTime(). Most likely, the author was falling back on his familiar use of the GregorianCalendar object for doing date/time manipulation.
On a side note, use of setGregorianChange to get this information seems... abusive of the API. The method is used to set "the point when the switch from Julian dates to Gregorian dates occurred. Default is October 15, 1582 (Gregorian). " (javadoc) It may work to make the given calculation, but it makes things pretty hard to understand from a code maintenance point of view.

Related

Java 8 -- How do I calculate (milli)seconds from now using xsd:duration

I feel like this question has been asked in one way or another, but I'm still not confident of my result.
I have an xsd:duration which will give me a desired expiration described in years, months, days, and seconds. I can collect the integer values of these parts with, for example, duration.getYears() or duration.getMonths().
Because my chosen db is Cassandra, I want to exploit the TTL option, which will automatically expire an inserted row after a specified number of seconds.
The critical part is getting from xsd:duration to an integer/long value of seconds which respects the Gregorian calendar (where 1 month from now is not simply 30.41 days, but 31).
At the moment, I'm using the following code:
LocalDateTime then = LocalDateTime.now().plusYears(duration.getYears()).plusMonths(duration.getMonths()).plusDays(duration.getDays()).plusHours(duration.getHours()).plusMinutes(duration.getMinutes()).plusSeconds(duration.getSeconds());
long ttlMillis = then.toInstant(ZoneOffset.UTC).toEpochMilli() - Instant.now().toEpochMilli();
Is there a quicker/cleaner way to do this?
I'm also not sure if I should worry about large durations... My particular use cases wouldn't call for anything larger that 2 years.
Informational note for all:
You are talking about javax.xml.datatype.Duration, not java.time.Duration.
Your questions:
a) Is there a quicker way to do this (using Java-8)? Hardly. The designers of JSR-310-team responsible for the new date- and time library in Java-8 have not cared much about the bridge to the existing XML-classes in JDK. So there is no direct way to convert from xml-duration to any kind of JSR-310-duration.
Keep also in mind that the JSR-310-classes Period (with state consisting of years, months and days) and Duration (with state consisting of seconds and nanoseconds) are not really designed for representing an xml-duration (which has more units as seen in your code). So I doubt if we might see a well-defined bridge between JSR-310 and XML in the future (maybe only on millisecond base?). The sign handling is also completely different in JSR-310 and XML. So be cautious if you have negative sign in xml-duration.
b) Is there a cleaner way to do this (using Java-8)? Yes, a little bit. One thing to consider is: I would use the clock as time source for the actual instant only once and not twice as you have done it. Example for this (very) minor improvement:
Instant now = Instant.now();
LocalDateTime start = now.atOffset(ZoneOffset.UTC).toLocalDateTime();
LocalDateTime end =
start.plusYears(duration.getYears())
.plusMonths(duration.getMonths())
.plusDays(duration.getDays())
.plusHours(duration.getHours())
.plusMinutes(duration.getMinutes())
.plusSeconds(duration.getSeconds());
long deltaInMillis = end.toInstant(ZoneOffset.UTC).toEpochMilli() - now.toEpochMilli();
Second thing to consider: The xml-duration class is designed for interoperation with java.util.Date. So you also have this short alternative:
Date start = new Date();
long deltaInMillis = duration.getTimeInMillis(start);
This alternative is not only much shorter, but is probably also more precise because it takes into account the millisecond part. According to the documentation you should only worry about the correctness if you have duration items in long range (excessing the range of int). Another topic is the relationship to any hidden timezone calculation. I have not seen any hint in the documentation, so this is maybe the only item which can make you worry (either local timezone? or UTC? - not tested).
c) Why worry about large durations? Even if your duration is larger than let's say some centuries possibly crossing the validity limits of historic gregorian calendar, you should keep in mind that xml-duration only uses the proleptic gregorian calendar, not the historical one. And LocalDateTime uses the same proleptic gregorian calendar, too. If such a large duration is related to any real data is another good question however.

Best way to store time in java, in format of HH:MM

After doing my research I wasn't able to find a method or data type that should be used for variable in order to store time in format of HH:MM, I did find methods to get this from a string like "14:15:10", but I think this is not the best way, as I'll need to add or subtract from time. I tried doing this as a double, but ran into following issue, when you have a time like 05.45 stored and add 0.15 (or 15 minutes) to it, the result is 05.60 where as with HH:MM format you'd expect it to be 06.00.
I'm looked through java documentation and still am, but can't seem to find any way to achieve this, closest I got to is date format like dd/mm/yyyy hh:mm:ss
Use Joda Time. It provides much better operations to do date/time manipulation than standard java dates. If you want to use internal JDK classes, use java.util.Date.
Since Java 8, you can use the new API for dates and times, including Instant, ZonedDateTime and LocalDateTime. This removes the use for the third party library Joda time. It also makes calculations more easy and correct. The advice below is a bit dated but still has some good points.
—————
What you definitely should NOT do is store them in your own custom format. Store the Long value that represents the Unix Epoch.
A DateTime is nothing more than a number to a computer. This number represents the amount of seconds (or milliseconds) since 1970-01-01 00:00:00 UTC. It's beyond the scope of this answer to explain why this date was universally chosen but you can find this by searching for Unix Epoch or reading http://en.wikipedia.org/wiki/Unix_time.
This also means there is NO timezone information stored in a DateTime itself. It is important to keep this in mind when reasoning about dates and times. For things such as comparing DateTime objects, nothing concerning localization or timezones is done. Only when formatting time, which means as much as making it readable to humans, or for operations such as getting the beginning of the day, timezones come into play.
This is also why you shouldn't store the time like 20:11:15 in a string-like format because this information is meaningless without timezone information. I will give you 1 example here: Consider the moment when the clock is moved back 1 hour, such as when moving away from daylight savings time. It just happened in a lot of countries. What does your string 02:30 represent? The first or the second one?
Calculations such as subtraction are as easy as doing the same with numbers. For example: Date newDate = new Date(date1.getTime() - date2.getTime());. Or want to add an hour to a date? Date newDate = new Date(oldDate.getTime() + 1000 * 60 * 60);
If you need more complex stuff then using Joda time would be a good idea, as was already suggested. But it's perfectly possible to just do even that with the native libraries too.
If there's one resource that taught me a lot about date/time, it would be http://www.odi.ch/prog/design/datetime.php
Java has java.sql.Time format to work with time-of-day values. Just import it and create variables.
import java.sql.Time;
//now we can make time variables
Time myTime;
Just saw it on https://db.apache.org/derby/docs/10.4/ref/rrefsqlj21908.html
The answer that is right for your case depends on what you want to do.
Are you using a RDBMS as your persistence engine?
If so, are you already working with legacy data formats or are you building a database from the ground up?
Are you simply storing this data, or will you be doing extensive date arithmetic and/or precedence calculations?
Are you in one time zone or do you need to work with time instants across many time zones?
All of these things are important and factor into your decision of how to represent your times and dates.
If your needs require a lot of date arithmetic (eg. determining days between dates) or sorting based on timestamps, then consider using a floating point date format. The advantage of using a numeric format for timestamps is that doing date arithmetic and comparison/sorting operations becomes trivial; you merely do simple arithmetic. Another advantage is that floats and longs are primitive data types. They do not need to be serialized, they are already extremely lightweight, and everything you need to use them requires no external dependencies.
The main disadvantage to using numeric formats for timestamps is that they are not human friendly. You'll need to convert them to and from a String format to allow users to interact. Oftentimes, this is worth the effort. See: How do I use Julian Day Numbers with the Java Calendar API?
I recommend that you consider storing timestamps as Julian Day Numbers (JDNs) or Modified Julian Day Numbers (MJDs). Both will represent dates and times to millisecond precision using an 8 byte float. Algorithms for converting to and from display formats for both of these are highly standardized. They confer all the advantages of using numeric dates. Moreover, they are defined only for GMT/UTC which means that your timestamps are already universalizable across time zones right out of the box (as long as you localize properly).
If you dont want the full date object, your best bet is to store it in a string, but I personally would still recommend date as it also contains a lot of convenient methods that will come in handy. You can just get the time as a whole from a date object and ignore the rest.
In terms of "storing" a date, you should use a long. This is how the system sees it and how all calculations are performed. Yes, as some point out you will eventually need to create a String so a human can read it, but where people run into trouble is when they start thinking of a date in terms of format. Format is for readability, not for calculations. java.util.Date and java.util.Calendar are fraught with issues (Effective Java, Bloch, et. al. has plenty to say about it) but are still the norm if you need handy date operations.

Why was Date.getTimezoneOffset deprecated?

The documentation for Date.getTimezoneOffset says:
Deprecated. As of JDK version 1.1, replaced by
-(Calendar.get(Calendar.ZONE_OFFSET) + Calendar.get(Calendar.DST_OFFSET)) / (60 * 1000).
Why was it deprecated? Is there a shorter way (Apache Commons?) to get the offset from UTC in hours/minutes? I have a Date object ... should I convert it to JodaDate for this?
And before you ask why I want the UTC offset - it's just to log it, nothing more.
There are 2 questions here.
Why was Date.getTimezoneOffset deprecated?
I think it is because they actually deprecated nearly all methods of Date and moved their logic to calendar. We are expected to use generic set and get with the parameter that says which specific field we need. This approach has some advantages: less number of methods and the ability to run setters in a loop passing a different field each time. I personally used this technique a lot: it makes code shorter and easier to maintain.
Shortcut? But what's wrong with call
Calendar.get(Calendar.DST_OFFSET) comparing to
Calendar.getTimeZoneOffset()
As far as I can see the difference is 6 characters.
Joda is a very strong library and if you really have to write a lot of sophisticated date manipulation code switch to it. I personally use the standard java.util.Calendar and don't see any reason to use external libraries: good old calendar is good enough for me.
All of the date manipulation logic was moved out of Date once the Java implementers realized that it might need to be implemented differently for different types of calendars (hence the need to use a GregorianCalendar to retrieve this info now). A Date is now just a wrapper around a UTC time value.
Take care before you paste code from this page.
Perhaps just me but I believe that in order to get the tz offset in minutes you need to do
int tzOffsetMin = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET))/(1000*60);
rather than what the Javadoc says, which is:
int tzOffsetMin = -(cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET))/(1000*60);
Calendar.ZONE_OFFSET gives you the standard offset (in msecs) from UTC. This doesn't change with DST. For example for US East Coast timezone this field will always be -6 hours regardless of DST.
Calendar.DST_OFFSET gives you the current DST offset (in msecs) - if any. For example during summer in a country that uses DST this field is likely to have the value +1 hour (1000*60*60 msecs).

Migrating from Java Calendar to Joda Date Time

Previously, when I first design a stock application related software, I decide to use java.util.Date to represent date/time information of a stock.
Later, I realize most of the methods in java.util.Date is deprecated. Hence, very soon, I refactor all my code to make use of java.util.Calendar
However, there is 2 shortcomings I encounter.
Construct java.util.Calendar is comparative slower than java.util.Date
Within the accessors getCalendar method of Stock class, I need to clone a copy, as Calendar is a mutable class
Here is the current source code for Stock.java
Recently, I discover Joda-Time. I do the following benchmarking, by creating 1,000,000 java.util.Date, java.util.Calendar and org.joda.time.DateTime. I found org.joda.time.DateTime performs better than java.util.Calendar, during instantiation.
Here is the benchmarking result.
This instantiation speed is important, especially many instance of Stocks will be created, to represent a long price history of a stock.
Do you think is it worth to migrate from Java Calendar to Joda Date Time, to gain application speed performance? Is there any trap I need to pay attention to?
Note that java.util.Date is mutable too - so if it's a problem now you're using Calendar, it would have been a problem using Date too. That said, using Joda Time is definitely worth doing just because it's a much, much better API.
How certain are you that performance is actually an issue in your particular app? You say there will be "many instances" of Stock created... how many? Have you profiled it? I wouldn't expect it to actually make a significant difference in most situations. It's not obvious from your benchmarking graph what you're actually measuring.
Moving to Joda Time is a good idea in general, but I would measure the performance to see how much difference it really makes for you.
Why do you need a Calendar in your Stock class? I think using a Date to represent a point in time is fine. This seems to be what you want, because you want the Calendar object in the a stock to be immutable, which the Date class should be, if you ignore the deprecated methods.
You can use a temporary Calendar when you need to do time operations on a Date outside the Stock class:
Calendar calendar = Calendar.getInstance();
calendar.setTime(stock.getDate());
System.out.println(calendar.getYear());
Like this you can still store a Date in your Stock class, which should have the best performance when only store and retrieve Stock objects from a data storage. If you do several operations at once you can also reuse the same Calendar object.
If you don't like the Calendar interface you could still use Joda Time to do the time operations. You can probably convert dates to and from Joda Time if needed, to do time operations, and still store Date objects in your Stock class.
If java.util.Calendar instances to be replaced with org.joda.time.DateTime are parsed and/or formatted to a particular pattern, e.g.
String format = "YYYY-MM-dd HH:mm:ss";
Within method signatures for parameter and return types, as well as variable declarations
and instantiations, repace whole word occurrences of the class names Calendar (with
DateTime) and SimpleDateFormat (with DateTimeFormatter), respectively
Replace the formatter instantiation statement, e.g.
formatter = new SimpleDateFormat(format);
with
formatter = DateTimeFormat.forPattern(format);
Replace calls to methods of `SimpleDateFormat', e.g.
String dateStr = formatter.format(Calendar.getInstance().getTime());
with
String dateStr = DateTime.now().toString(formatter);
and
formatter.parse(dateStr);
with
DateTime.parse(dateStr, formatter);
I used Joda in the past, and it is an awesome library.
In terms of performance, you'll have to test it, unfortunately. But refactoring your code seems too much. Personally, I used Date throughout my whole application (including DB store and retrieve), and used Joda only when I needed data manipulation. Joda calculates fields only when needed, so I guess the overhead will be much lower than using Java API classes; furthermore, you won't have object version issues to transfer and handle Date objects in your DB, serialize objects and such. I don't expect Joda to break such compatibility, but it is less likely using Date.
It is always better to move to joda-time in general. But it it is really worth to move to the joda-time for your project is based on your use-cases pertaining to the date usage. Look at slide number 46 in the presentation for performance related numbers for some of the operationslink text

Which method should I use?

I'm an intermediate java coder, writing a librarian Java app, and for some reason I just can't figure out whether I should use dueDate.after(today) OR dueDate.before(today) method as to deciding if the book is overdue. I've gotten quite some contradictory values by typing both the methods. Hence, I'm also assuming there is some other bug in my code as well, so it would be nice if you can conform which is the correct method so that I can move on the fixing the other bug.
You need dueDate.before(today): the due date is before today; the due date is in the past, so the book is past due.
Maybe it's easier if you swap the objects around? You'd get today.after(dueDate) and if you read that out loud, it suddenly becomes quite clear: "if today is after the due date, then ..."
Remember that the before and after methods perform a < (or >) comparison, rather than a <= (or >= comparison). That is what is meant by the word "strictly" in the API documentation.
Also, Java Date objects are really an instant in time, rather than what people usually think of as a "date". That is, it won't just compare the day, but the time of day.
If you want to compare only the day, without checking the time during that day, create all of your due dates to be at a specific time, like midnight. For example, suppose that a book is due October 26. The due date could be midnight, October 27.
boolean overdue = !now.before(dueDate);
The somewhat awkward negation accounts for the case when it is now exactly 12:00 AM Oct. 27.
dueDate.before(today) would translate to the actual dueDate of the book occurring before today, meaning that it is actually overdue. This is probably what you want (assuming you are checking for true)
the other side of things
dueDate.after(today) would translate to the actual dueDate of the book occurring after today, meaning that it is not yet over due.
The only difference between !dueDate.after(today) and dueDate.before(today) is the result when both dates are exactly the same - presumably a book is not overdue when returned on the due date, so dueDate.before(today) should be correct.
As for your unspecified other problems: are you aware that java.util.Date represents a millisecond-precision point in time, not a calendar date? That means that in order to use its comparison methods for calendar dates, you have to make very sure you set the time components to zero when creating your Date instances. Another cause of problems could be time zone differences.
It depends on what you want to achieve. Is dueDate the date you want to set when lending a book? The due date is derived from the lending date of the book, so I would try an approach like book.isDue(today) assuming that the book object contains the lending and due dates as attributes.
With questions like this it helps if you make it explicit for yourself which objects are involved and what their relations are before you design the actions between the objects.

Categories

Resources