Java Calendar/Date Minvalue Supported on DB/Rest - java

I'm using Spring Boot, and HSQLDB file,
When i use:
calendar.setTimeInMillis(-9223372036854775808L);
calendar.setTime(new Date(Long.MIN_VALUE));
and and store the model,
after i call rest client, i get invalid date, when i check it, it returns some positive value instead of negative one :| what should i use as min_Value.
i thought it may be SQL issue, i changed temporary variable type from timespan to Date, but didn't worked again, i no longer sure what is the case of this issue, and what nuber i should use, every one talk about min value, some one talked about around -8.......L too that work in JS, but it didn't worked here too :|

Avoid ancient date-time values
Many reasons to not use that minimum number as a date value. As commented, standard SQL does not permit such ancient dates. No database implementation I know of supports that value. And using a date-time for historical values is fraught with problems and issues, and ill-advised.
Use epoch as a flag value
If you are looking for an arbitrary value to use as a flag such as "no value intended" while avoiding the use of nulls, then I suggest using the Java and Unix epoch of first moment of 1970 in UTC. If you know your system will never store any date-time that far back as a valid value, this will work well. And 1970-01-01T00:00:00Z is easily recognized by many programmers, DBAs, and SysAdmins as the common epoch and therefore likely to be a special value.
java.time
Avoid using the Date and Calendar classes. These troublesome classes and their siblings are now legacy, supplanted by the java.time classes.
These classes include a constant for that epoch value: Instant.EPOCH
Similar Question: Minimum date in Java

Related

Is there a way to represent BC dates with java.util.date?

Yes, I understand that java.util.Date is extremely outdated. That being said, is there a way to represent dates before 1 CE using this class, or must I migrate to a different class?
Trivially, no. There is no way to represent dates with java.util.Date at all. Any date.
j.u.Date is a misnomer, and is obsolete API you should not be using. It actually represents an instant in time, unconnected to a timezone, and therefore, unconnected to the concept of years, months, and days. That's why e.g. .getYear() is deprecated, and why the only field that j.u.Date has is a long containing epochmillis.
You must migrate to java.time. Specifically, java.time.LocalDate.
Note that you can represent moments in time that, once you place them in a timezone, are before 1CE just fine. epochmillis-in-a-long (which is what System.currentTimeMillis() represents, and for which j.u.Date is a really really bad wrapper, but java.time.Instant is the right thing to use if you want that) - their range is a few million years in both directions.

Oracle database: using Char(X) or Numeric(X) instead of Date

I have found some issues with the date type in Oracle databases. I have to manage an important amount of data, and they don't seem to work as well as expected with indexes and other stuff. The important thing is that I have decided to use another type for it.
My options are:
numeric(8) for "date" and numeric(6) for "time"
char(8) for "date" and char(6) for "time"
The fields are formatted as YYYYMMAA for date and HHMMSS for time.
The order of priorities (pondered) are:
Performance querying the fields separately (x3.5)
Performance querying the fields joined as one (date + time) (x3)
Usability from java (x2)
Legibility of the database (x1)
Which type would you suggest to use and why?
Thanks! :)
I would recommend to use still a date type. It will be stored as a number anyway ;) . But if you preffer to store it as a number or char, the 20151019 as a number makes more sense :) (also from size & performance perspective) btw, date format will be even smaller
ISO 8601
When you must serialize a date-time value as a string, use the standard ISO 8601 formats. Here are examples of a few of the formats:
Date-only example: 2015-10-18
Date-time example: 2015-10-18T14:26:16Z
Week-of-year: 2015-W42
This entire standard is surprisingly well thought-out and practical. The strings alphabetical order also happen to be chronological (when in UTC, and when consistent with resolving to whole or fraction of the second).
The hyphens are optional, considered by the spec to be the the "basic" version of the formats; I suggest including the hyphens unless storage/memory is critically scarce. The hyphens make the strings recognizable as date-time representations, and are easier to read by humans.
When creating reports, exporting data, writing XML or JSON, or otherwise exchanging data, I suggest almost always using these standard formats. Both (a) the new java.time framework built into Java 8 and later, (b) the Joda-Time library use these formats by default when parsing and generating string representations of date-time values.
Specifications Discordance
Note that while both ISO 8601 and the SQL standard are decades old, they seemed to have not crossed paths. The SQL standard has similar formats but not quite the same. Specifically ISO 8601 uses a T between the date and time-of-day portions whereas the SQL spec never does so.
Also some proprietary types use their own string formats, such as Oracle 11g using DD-MON-YY as the default for DATE type, for example '13-NOV-92'.
java.time
The java.time framework built into Java 8 and later has extended the ISO 8601 format for date-time by appending the name of the time zone in brackets.
The standard uses only an offset-from-UTC. A true time zone is an offset plus a set of rules for making adjustments for anomalies such as Daylight Savings Time (DST).
Use The Data-Type, Luke
Like the others commenting, I strongly recommend you learn and use your database’s native data types for date-time work. Some like SQLite have weak support for date-time, but most have decent to excellent support (such as H2 and Postgres).
These data types vary widely. The SQL spec defines some, but some databases such as Oracle additionally have proprietary types. Often those proprietary types are old outmoded types.
Even the standard data types are not so standard. You should play around and experiment outside your project so as to cement your understanding of their behavior.
The "issues" you experienced are most likely a misunderstanding of the specific type or of date-time handling in general. If so, rolling you own data type (via strings) will only exacerbate your problems in the long run. Invest some time in searching StackOverflow to learn about date-time handling. The subject of date-time is surprisingly tricky.
Numbers
As for using numbers as a roll-your-own date-time type, nearly all the native date-time data types use numbers internally. So no performance advantage in doing your own.

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.

How should date properties be defined in a java class?

I have a simple java object with several date properties and I always seem to change my mind on how to define them. Should the properties be defined as date objects or strings? The object is going to be used in struts 1.3 application with iBatis as the persistence layer and mysql as the database. The database columns are defined as datetime and they can possibly be null and I usually don’t care about the time portion.
public Date getForcastDate();
or
public String getForcastDate();
Most of the existing code base uses strings, but that just doesn’t seem quite right to me.
Keep your dates as Dates. That way you can change formatting depending on locales, check for invalid dates, sort by them etc.
By keeping them as strings you're potentially throwing away data (e.g. milliseconds if your formatter doesn't use them) and definitely behaviour.
Using strong-typing (e.g. keeping them as Dates) will aid in terms of development. Your method signatures become clearer, refactoring using IDE tooling becomes easier etc. Otherwise you end up with APIs that talk in nothing but strings, it's trivial to mix up parameters, and it becomes impossible to work out what's going on.
Tip: Check out Joda-Time as a better alternative to the standard java.util.Date.
I would use Date object because it cleaner to store a Date and convert it to a String when needed. Otherwise you have to hard code a formatted date into a String field.
I would never use Strings in this cas as what would today be 8/3/11 or 3/8/11 or 2011-03-08. This is really a specific case of trying to use the most restrictive type/class possible for a variable. This is so that you can understand its behaviour more fully, both by having a restricted or specialised set of methods and by helping documentation of other classes using it. Using a Date here would allow you to use a Calendar object to add days or months. Conversion to or from a string only needs to be done for input and output.
In practice if they were only dates I would crete my own Date class so could ignore times or use JodaTime which provides easier manipulation than the java Date
In my code I always use the most high level object. In this case I would suggest - Calendar. Here is separate discussion about Date and Calendar. I always think this way - converting Calendar/Date to String is simple - use SimpleDateFormatter. But very often you will need to do something with the date (add several days or hours, subtract a year, handle timezones etc) and then each time you would have to convert it from String to Calendar/Date.
Date if you had to, but java.util.Calendar would probably be more appropriate nowadays. With a String you'd have to worry about format like #jzd mentioned. With Calendar, you can easily switch between formats. Also Calendar lets you get at the date with Calendar.getTime()

Why were most java.util.Date methods deprecated?

When you look at the javadoc of the java.util.Date class, most of the methods are deprecated. Why was this done?
Well, for two related reasons. It was a very poor implementation of the concept of Dates and Times and it was replaced by the Calendar class.
The Calendar class, although an improvement, leaves a lot to be desired as well, so for serious Date/Time work, everyone recommends Joda-Time. Java 8 brings the new java.time.* package, inspired by Joda-Time, defined by JSR-310, and intended to supplant the old Date/Calendar classes.
Edit: In response to the specific question of why the implementation is poor, there are many reasons. The JavaDoc sums it up as follows:
Unfortunately, the API for these functions was not amenable to internationalization.
In addition to this general deficiency (which covers issues like the lack of a Time Zone component as well as the date formatting which is better handled in DateFormat and the inability to have a non-Gregorian calendar representation), there are specific issues which really hurt the Date class, including the fact that year is presented in an offset of 1900 from Common Era year.
Calendar has its own problems, but even as early as JDK 1.1 it was obvious that java.util.Date was not going to cut it. Even though Calendar is arguable the worst JDK API, it has taken until version 7 to attempt to address it.
Date is mutable
Date doesn't have support for time zones
The latter led to it being replaced by Calendar. And the former, combined with the ease-of-use, lead to both being replaced by Joda-Time / JSR-310 (java.time.* package)
They're deprecated because Date was written as fast as possible back in the day when they wanted to rush the JDK out the door.
It turns out the Dates and Calendars are Hard. So, they created the Calendar class, which much more thought, in order to handle the Hard Parts of working with calendars.
They deprecated the Date methods and delegated to Calendar because they didn't want to change the behavior of the existing Date methods, and possibly break existing applications.
Here's a good answer straight from Oracle: http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html
A long-standing bugbear of Java developers has been the inadequate support for the date and time use cases of ordinary developers.
For example, the existing classes (such as java.util.Date and SimpleDateFormatter) aren’t thread-safe, leading to potential concurrency issues for users—not something the average developer would expect to deal with when writing date-handling code.
Some of the date and time classes also exhibit quite poor API design. For example, years in java.util.Date start at 1900, months start at 1, and days start at 0—not very intuitive.
... java.util.Date represents an instant on the timeline—a wrapper around the number of milli-seconds since the UNIX epoch—but if you call toString(), the result suggests that it has a time zone, causing confusion among developers.
I don't know the official reason why it has been deprecated, but as far as I can tell GregorianCalendarand Joda-Time support operations on dates, meaning that you can add, for instance, a day to a date and have its month and year updated accordingly.
For instance, say you want to compute the day after the current date and today is May 31st; with java.util.Date, you just have getDays() +1, which returns 32, and you have to handle the knowledge that the current month doesn't have 32 days by yourself; with GregorianCalendaror Joda.time, adding a day to May 31st results in an object representing June 1st, hiding the complexity from your sight.

Categories

Resources