Why was Date.getTimezoneOffset deprecated? - java

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

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.

conversion of unix timestamp into date returning wrong time [duplicate]

I have 2 different computers, each with different TimeZone.
In one computer im printing System.currentTimeMillis(), and then prints the following command in both computers:
System.out.println(new Date(123456)); --> 123456 stands for the number came in the currentTimeMillis in computer #1.
The second print (though typed hardcoded) result in different prints, in both computers.
why is that?
How about some pedantic detail.
java.util.Date is timezone-independent. Says so right in the javadoc.
You want something with respect to a particular timezone? That's java.util.Calendar.
The tricky part? When you print this stuff (with java.text.DateFormat or a subclass), that involves a Calendar (which involves a timezone). See DateFormat.setTimeZone().
It sure looks (haven't checked the implementation) like java.util.Date.toString() goes through a DateFormat. So even our (mostly) timezone-independent class gets messed up w/ timezones.
Want to get that timezone stuff out of our pure zoneless Date objects? There's Date.toGMTString(). Or you can create your own SimpleDateFormatter and use setTimeZone() to control which zone is used yourself.
why is that?
Because something like "Oct 4th 2009, 14:20" is meaningless without knowing the timezone it refers to - which you can most likely see right now, because that's my time as I write this, and it probably differs by several hours from your time even though it's the same moment in time.
Computer timestamps are usually measured in UTC (basically the timezone of Greenwich, England), and the time zone has to be taken into account when formatting them into something human readable.
Because that milliseconds number is the number of milliseconds past 1/1/1970 UTC. If you then translate to a different timezone, the rendered time will be different.
e.g. 123456 may correspond to midday at Greenwich (UTC). But that will be a different time in New York.
To confirm this, use SimpleDateFormat with a time zone output, and/or change the timezone on the second computer to match the first.
javadoc explains this well,
System.currentTimeMillis()
Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
See https://docs.oracle.com/javase/7/docs/api/java/util/Date.html#toString().
Yes, it's using timezones. It should also print them out (the three characters before the year).

Scala/java sanitize day of month above 31 or below 1?

Using JodaTime library (although I am a bit flexible). I realized some of the inputs coming in are breaking Joda time because the days of the month are above 31 or below 1 (because of client-side code).
I am using the LocalDate object for calendar manipulation. Is there a library or method to easily sanitize the dates so the input doesn't start throwing exceptions?
Some Scala code I am using now: EDIT: Fixed code
val now = new LocalDate();
val workingDate = now.withYear(y).withMonthOfYear(m).withDayOfMonth(d).withDayOfWeek(DateTimeConstants.SUNDAY)
ymdStart = toTimestampAtStart( workingDate )
For clarification, the goal here is to convert the date to a proper date, so if a user submitted July 38, it would convert to August 7. There's an incoming URL structure causing a lot of this and it looks like /timeline/2012/07/30.
For reasons of pure exercise (I agree normalization seems to be bad practice) I'm now just purely curious if there are libraries that deal with such a problem.
Thanks!
Final Update:
Like the answer points out, normalization was a poor idea. I did a lot of re-factoring on the client side to fix the incoming variables. This is the code I ended up using:
ymdStart = new Timestamp( toTimestampAtStart( new LocalDate(y,m,d).withDayOfWeek(1) ).getTime - 86400000 )
ymdEnd = new Timestamp( ymdStart.getTime + 691200000 )
First of all, a LocalDate is immutable, so each chained with...() is creating a new date.
Second, it is a well-known antipattern to update pieces of a date one at a time. The end result will depend on the current value of the date, the order in which you update the pieces, and whether or not the implementation "normalizes" dates.
In other words NEVER update a date/time piecemeal.
Assume for a minute that the implementation "normalizes" (i.e. corrects for overflow) invalid dates. Given your code, if today's date was 31-Jan-2011 and you did
now.setMonth(FEBRUARY);
now.setDayOfMonth(12);
the result will be 12-March-2011. The first statement sets the date to 31-February, which gets normalized to 03-March, then the day gets set to 12. Ah, you say, you can just set the day-of-month first. But that doesn't work for different starting points (construction of which is left as an exercise).
And from your question I surmise that JodaTime throws exceptions rather than normalize, which is anothe reason for not doing it this way.

Using GregorianCalendar.setGregorianChange for calculating time difference

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.

Categories

Resources