java-joda datetime classes (current system time)? - java

I'm "Converting" some c# code to java and I've come to a point where things get weird.
I'm using the joda LocalTime object as I'm dealing with time comparison only.
In c# to get the current system time we use the following code:
DateTime.Now.TimeOfDay //returns Timespan as wanted
But in Java-joda I can't find such thing and I'm forced to the following:
LocalTime nowLocalTime=new LocalTime();
LocalTime currenTime=new LocalTime(nowLocalTime.getHourOfDay(),nowLocalTime.getMinuteOfHour(),00);
Is there an alternative to that, a much sweeter way to do this? (I must pack it into LocalTime to make the use of the .Compare method).

You're looking for LocalTime.now()

Related

How to know if a Date object represents only Time in Java?

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.

Fast way to get the current Calendar object in Java

Given a method that needs to use the values of the current day/month/year on every invocation and which is invoked several (millions or more) times per second, is there any faster way of implementing that functionality, other than creating a Calendar object for the current time on every invocation?
Using Calendar.getInstance() or calendar.setTime() (with time field recalculation) is overly expensive to do many times per second.
Standard Java solutions are preferable (e.g., over using third party libraries).
To get the current date/time, I find that LocalDate.now() is faster than Calendar.getInstance(). The LocalDate class can be found in the java.time package, which is new since Java 8 (Of course, if you want to maintain compatibility with old Java versions, that may not be an option).
The best solution within the scope of standard java (no 3rd party-libraries) is using the class LocalDate. So far this answer is identical to that of #Chronio, but I differ in use. The factory method now() cannot be so quick because it exploits the system timezone - maybe even using a synchronized approach anywhere in the depth of TimeZone.getDefault().
But the class LocalDate is very quick if you use its factory methods with arguments of year, month and day-of-month. Here you are just setting the state members without any timezone calculation and without any calculation of gregorian calendar math (okay only quick year-dependent length-of-month-check is involved). Just see the source code.
use the Date, instead of Calendar class it will give you the current date

Which Android APIs to use for simple date and time functions

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?

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

Comparing if two Date instances refer to the same day

I have two Java instances of java.util.Date and I have to find out if they refer to the same day.
I can do this the hard way, taking the dates apart and compare the days, making sure the years match too.
Since this is such a common problem, I expect there to be an easier solution to this problem.
Thanks!
Instances of java.util.Date refer to instants in time. Which day they fall on depends on which time zone you're using. You could use a java.util.Calendar to represent an instant in a particular time zone...
... or you could use Joda Time instead, which is a much, much better API. Either way, you'll have to know what time zone you're interested in.
In Joda Time, once you've got a relevant time zone, you can convert both instants to LocalDate objects and compare those. (That also means you can compare whether instant X in time zone A is on the same day as instant Y in time zone B, should you wish to...)
I use the DateUtils class by Apache Commons Lang 2, it provides the isSameDay(Date,Date) method.
Update:
Here the link to Apache Commons Lang 3.
From elsewhen on StackOverflow
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
return fmt.format(date1).equals(fmt.format(date2));

Categories

Resources