Introduction: Any enterprise application needs to deal with time issues. The application needs to know the current point-in-time and the next point in time, and sometimes they must also compute the path between the two points in time. Using JDK to accomplish this task will be very painful and tedious. Now let's look at Joda time, an easy-to-use open source timing/Date library for the Java™ platform. As you know in this article, Joda-time easily dissolves the pain and complexity of dealing with dates and times.
When writing an enterprise application, I often need to process the date. And in my latest project-Insurance industry-correcting date calculations is particularly important. Using Java.util.Calendar makes me a little uneasy. If you've ever used this class to deal with date/time values, then you know how troublesome it is to use it. So when I come in contact with an alternative to the joda-time--oriented date/Time library for Java applications-I decided to look into it. The result: I'm glad I did.
Joda-time makes time and date values easier to manage, manipulate, and understand. In fact, easy to use is the main design goal of Joda. Other goals include scalability, a complete set of features, and support for multiple calendar systems. And Joda is completely interoperable with JDK, so you don't have to replace all the Java code, just the part of the code that performs date/time calculations. Joda Large Projects
Joda is actually a large project that covers numerous alternative APIs for the Java language, so technically, using Joda and joda-time names to denote the same meaning is a mistake. But at the time of writing this article, the Joda-time API appears to be the only Joda API in active development state. Given the current state of Joda large projects, I think it would be OK to joda-time for short Joda.
This article describes and shows you how to use it. I'll introduce the following topics: Date/Time Substitution library Introduction Joda key Concepts Create joda-time objects to Joda manipulate time style to format time in Joda way
You can download the source code for the sample application that demonstrates these concepts.
Joda Introduction
Why to use Joda. Consider creating a casual moment in time--for example, January 1, 2000 0:0. How do I create a JDK object that represents this moment in time. Use Java.util.Date. In fact, this is not feasible, since every Java version of Javadoc since JDK 1.1 declares that Java.util.Calendar should be used. The number of constructors that are not favoured using in Date severely limits the way you create such objects.
However, Date does have a constructor that you can use to create an object that represents an instant in time (except "Now"). The method corrects the time zone using the number of milliseconds since the Greenwich Mean Time (also known as epoch) from January 1, 1970 to be a parameter. Given the importance of Y2K to the software development business, you might think I've memorized this value-but I didn't. So is Date.
So what about the Calendar? I will create the required instances in the following ways:
Calendar calendar = Calendar.getinstance ();
Calendar.set (Watts, calendar.january, 1, 0, 0, 0);
|
With Joda, the code should resemble the following:
datetime datetime = new DateTime (2000, 1, 1, 0, 0, 0, 0);
|
This simple line of code is not much different. But now I'm going to complicate the problem a little bit. Suppose I want to add 90 days to this date and output the results. With JDK, I need to use the code in Listing 1:
Listing 1. Add 90 days to a certain moment in JDK and output the results
Calendar calendar = Calendar.getinstance ();
Calendar.set (Watts, calendar.january, 1, 0, 0, 0);
SimpleDateFormat SDF =
new SimpleDateFormat ("E mm/dd/yyyy HH:mm:ss. SSS ");
Calendar.add (Calendar.day_of_month,);
System.out.println (Sdf.format (Calendar.gettime ()));
|
Using Joda, the code looks like listing 2:
Listing 2. Add 90 days to a certain moment and output the result in a Joda manner
datetime datetime = new DateTime (Watts, 1, 1, 0, 0, 0, 0);
System.out.println (datetime.plusdays). toString ("E mm/dd/yyyy HH:mm:ss. SSS ");
|
The gap between the two is widening (Joda uses a couple of lines of code, and the JDK is 5 lines of code).
Now suppose I want to output a date that is 45 days after the date of the last day of the current week of the next one months Y2K. Frankly speaking, I don't even want to use calendar to deal with this problem. Using JDK is too painful, even for a simple date calculation, such as the one above. It was at such a time years ago that I first learned the power of joda-time. Using Joda, the code for the calculation is shown in Listing 3:
Listing 3. Switch to Joda
datetime datetime = new DateTime (Watts, 1, 1, 0, 0, 0, 0);
System.out.println (Datetime.plusdays) plusmonths (1). DayOfWeek ()
. Withmaximumvalue (). toString ("E mm/dd/ YYYY HH:mm:ss. SSS ");
|
The output of Listing 3 is:
Sun 03/19/2000 00:00:00.000 |
If you are looking for an easy-to-use way to replace JDK date processing, then you really should consider Joda. If this is not the case, then continue to painfully use calendar to complete all date calculations. When you do this, you can use a few scissors to build the lawn and use an old toothbrush to clean your car.
Joda and JDK Interoperability
The lack of usability of JDK Calendar classes is quickly felt, and Joda makes up for it. Joda's designers also made a decision, and I think it was a successful build: JDK interoperability. Joda classes can be generated (but, as you'll see, sometimes using a more circuitous approach) Java.util.Date instances (and Calendar). This allows you to retain the existing JDK-dependent code, but can also use Joda to handle complex date/time calculations.
For example, after completing the calculation in Listing 3. I just need to make the changes shown in Listing 4 to return to the JDK:
Listing 4. Inserting the results of Joda calculations into JDK objects
Calendar calendar = Calendar.getinstance ();
datetime datetime = new DateTime (Watts, 1, 1, 0, 0, 0, 0);
System.out.println (Datetime.plusdays) plusmonths (1). DayOfWeek ()
. Withmaximumvalue (). toString ("E mm/dd/ YYYY HH:mm:ss. SSS ");
Calendar.settime (Datetime.todate ());
|
It's so simple. I completed the calculation, but I can continue to process the results in the JDK object. This is a great feature of Joda.
Back to the top of the page
Key date/Time concepts for Joda
Joda uses the following concepts that can be applied to any date/time library: Non-variability (immutability) instantaneous (Instant) temporal (Partial) chronology (chronology) time zone (Times zone)
I'll discuss each concept in turn for Joda.
Non-denatured
The Joda classes I discussed in this article are immutable, so their instances cannot be modified. (One advantage of immutable classes is that they are thread-safe). The API methods that I will show you for processing date calculations all return a new instance of the corresponding Joda class, while keeping the original instance unchanged. When you manipulate the Joda class through an API method, you must catch the return value of the method because the instance you are working on cannot be modified. You may be familiar with this pattern, for example, this is how java.lang.String's various methods of operation work.
Instant Sex
Instant represents an exact moment in time, expressed in milliseconds that are computed from epoch. This definition is the same as JDK, which is why any jodainstant subclass can be compatible with JDK Date and Calendar classes.
A more general definition is that an instant is a point in time that only occurs once and only once, and that the date structure can only appear once in a meaningful way.
Local Nature
A local time, as I will refer to it as a local time fragment in this article, which refers to a fragment of time. The instant specifies a precise moment in time relative to the epoch, in contrast to a local time fragment that is a time that can "move" back and forth, so that it can be applied to multiple instances. For example, June 2 can be applied to any moment of the second day of June of any year (using the Gregorian calendar). Similarly, 11:06 p.m. Can be applied to any day of any year and can only be used once a day. Local time fragments are still useful, even if they do not specify a precise moment in time.
I like to think of a local time fragment as a point in a repeating cycle, so that if the date build I'm considering can occur multiple times (that is, repetition) in a meaningful way, then it's a local time.
Chronology
The key to Joda essence-and its design core-is the chronology (its meaning is captured by an abstract class with the same name). In essence, chronology is a calendar system-a special way of calculating time-and is a framework in which calendar algorithms are executed. Examples of chronology supported by Joda include: ISO (default) Coptic Julian Islamic
Joda-time 1.6 supports 8 chronology, each of which can be used as a computing engine for a particular calendar system.
Time
A time zone is the location of a value relative to Greenwich, England, for calculating time. To understand exactly when an event occurs, you must also know where the event occurs. Any rigorous time calculation must involve a time zone (or relative to GMT), unless a relative time calculation occurs within the same time zone (such time zones are also important if the event has an interest in the parties in another time zone).
Datetimezone is a class that Joda libraries use to encapsulate location concepts. Many date and time calculations can be done without the time zone involved, but you still need to understand how Datetimezone affects Joda operations. The default time, the time retrieved from the system clock of the machine running the code, is used in most cases.
Back to the top of the page
Creating Joda-time Objects
Now, I'll show you some of the Joda classes that you'll often encounter when you take the library, and show how to create instances of these classes. variable Joda class
I'm not a fan of variable utility; I just don't think their use cases are suitable for widespread use. But if you think you do need to use the variable Joda class, the content of this section should be helpful to your project. The only difference between the readable and readwritable APIs is that the Readwritable class can change the encapsulated date/time value, so I'm not going to introduce that here.
All implementations described in this section have several constructors that allow you to initialize the encapsulated date/time. They can be grouped into 4 categories: using System time. Use multiple fields to specify an instantaneous moment (or a local time fragment) to achieve the most fine-grained precision that this particular implementation can support. Specifies an instantaneous moment (or local time fragment), in milliseconds. Use another object (for example, Java.util.Date, or another Joda object).
I'll introduce these constructors in the first class: DateTime. You can also use the content described here when you use the appropriate constructors for other Joda classes. Overloaded Methods