I want to compare 2 dates without the time, some posts in SO suggest to use Joda-Time API, but I don't understand how to use Joda-Time.
I can't find any post that include how to declare, what package to be imported. and what does method getDateOnlyInstance() return? An integer or what?
As to how to use Joda API, google it, pretty basic stuff, you need to have the correct jar's on your classpath. Get the latest version of the jar here: http://sourceforge.net/projects/joda-time/files/joda-time/2.3/ (or use maven or some other build tool).
What the getDateOnlyInstance() returns is a comparator, which when passed two DateTime-objects will compare them, but ignore the time-portion of the them, and only compare the dates (for instance, if you pass 2014-01-24 04:20:00 and 2014-01-24 13:37:00 they will be regarded as equal.)
DateTime is one of the central classes in JodaTime, and it is a representation of a date and a time (duh), much like the java.util.Date, but with one big difference: DateTime is actually usable. You can do fun operations like adding and substracting days, hours and minutes, set the time-portion of it to midnight, and construct representations of dates without getting any grey hairs in the meantime.
So download the zip for JodaTime from the link above, and place the joda-time-2.3.jar on your classpath, then you can use both DateTime and its comparator.
Related
I'm trying to save data about date and time to List. Let's say, I have List<Date>. I have 2 types of formatting of strings: dd/mm/yy and hh:mm. Well, I'm able to easily format and create an instance of java.util.Date using SimpleDateFormat. However, when I try to print the object, the one that I saved time data into prints something like this:
Thu Jan 01 06:30:00 AZT 1970
How do I differentiate between these two and get the following output instead:
06:30
Note: Years may start earlier than 1970.
Thanks for the help and appreciate the effort.
How to know if a Date object represents only Time in Java?
There is no way to do this reliably. Every value of Date that you are using to represent a time also represents a valid date. And you can't distinguish the two cases ... except by using an unreliable heuristic.
The real problem is that you should not use Date to represent times.
A Date represents a single point in the time continuum.
A time is either a duration or multiple time points depending on how you use it. (It depends on your use-case.)
In fact, you probably not be using java.util.Date at all. Date is legacy Java class that has many API flaws. It was superseded in Java 8 by the classes and interfaces in the java.time package. These provide distinct classes for the various different concepts.
I recommend that you read the Date-Time trail in the Oracle Java Tutorial to get a basic understanding. This will help you decide the correct classes to choose for your use-case.
Time is complicated in the real world, and it is complicated in Java too.
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
The set of date and time functions I need are pretty basic.
An object to represent a date/time (for convenience in function calls).
Conversion functions to and from y,m,d,h,m,s.
Format/parse functions to and from numeric-only localised string representation. Eg dd/mm/yyyy, yyyy-mm-dd, mm.dd.yyyy or whatever order and delimiters are locally expected.
A system function to get the current local date and time (timezones not required).
Compatible with the DatePicker widget.
Thread safe. Static functions available to both UI and worker (NDK) threads.
So far I've found that:
Calendar and GregorianCalendar can do the conversions, but they're clunky to use and they're not thread safe.
SimpleDateFormat can do the formatting, if I could only figure out which magic string to feed it! The default is not numeric.
Time has a nicer set of conversion functions, but has no date/time object and the parse/format functions are documented only indirectly. And it smells a lot more like Unix than Java.
So do I find a way to fix the thread safety and try to persuade SimpleDateFormat to give me what I need? Or do I give up and jump ship to Time? Or have I missed something?
Just to be clear, this is not a request for a library recommendation or a shopping list. It's a request for assistance on how to implement a specific set of functions using the given Android API. I'm looking for an expert on using these libraries to point out a path through the morass. I would hope that a well-written answer would benefit other readers also struggling with this part of Android.
Personally I find Joda-Time to be able to handle almost everything you need for date and time. Since it's just a .jar it should be able to be imported.
Here's how to use it, for the questions you asked specifically:
An object to represent a date/time - DateTime for immutable or MutableDateTime for one that you need to apply transformations to.
These objects have many methods for conversion, see the Joda-Time API for AbstractDateTime as an example, as all of Joda's classes extend AbstractDateTime
You can use String convertedToString = new DateTime().toString("yyyy-MM-dd") to get it as 2014-05-05. To reverse this, use this API: DateTimeFormatter parseDateTime(someStringThatRepresentsADate)
DateTime now = new DateTime() gives you now, as a DateTime object
You can get a DateTime object from several other classes, such as Calendar by doing something like DateTime fromCalendar = new DateTime(myCalendarObject)
See The FAQ for Joda on multi-threading
In order to import Joda into your Android project, assuming you're using Android studio and Gradle, see this answer: Android Studio: Add jar as library?
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).
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()