About joda-time

Source: Internet
Author: User

Reference: http://www.ibm.com/developerworks/cn/java/j-jodatime.html

Introduction:Any enterprise application must handle time issues. The application needs to know the current time point and the next time point, and sometimes they must calculate the path between the two time points. Using JDK to complete this task will be very painful and cumbersome. Now let's take a look at joda time, an easy-to-use open-source time/date library for the Java platform. As you have learned in this article, joda-time easily resolves the pain and hassle of processing dates and times.

January 1, 2000 00:00

With joda, the code should be similar to the following:

Datetime = new datetime (2000, 1, 1, 0, 0, 0, 0 );

Add 90 days to a moment in the form of joda and output the result

Datetime = new datetime (2000, 1, 1, 0, 0, 0, 0 );
System. Out. println (datetime. plusdays (90). tostring ("yyyy/mm/dd hh: mm: Ss. Sss "));

Output: 2000/03/31 00:00:00. 000

 

Directly pass different objectsDateTimeConstructor

// Use a calendar
Java. util. Calendar calendar = obtaincalendarsomehow ();
Datetime = new datetime (calendar );
// Use another joda datetime
Datetime anotherdatetime = obtaindatetimesomehow ();
Datetime = new datetime (anotherdatetime );
// Use a string (must be formatted properly)
String timestring = "2006-01-26t13: 30: 00-06:00 ";
Datetime = new datetime (timestring );
Timestring = "2006-01-26 ";
Datetime = new datetime (timestring );

 

ReadablePartial

Not all of the date issues that the application needs to handle are related to a complete time point in time, so you can handle a local time point. For example, sometimes you are concerned about the year, month, or day of the day, or even the day of the week. Use by joda designersReadablePartialThe interface captures this concept of local time, which is an immutable local time segment. The two useful classes used to process such time segments areLocalDateAndLocalTime:

  • LocalDate: This class encapsulates a combination of years, months, and days. When the geographic location (Real-Time Zone) becomes unimportant, It is very convenient to use it to store dates. For exampleDate of birthIt may beApril 16, 1999From a technical point of view, however, you do not know any other information about the date while saving all business values (for example, the day of the week or the time zone where the person was born ). In this case, you should useLocalDate.

    Sample ApplicationSystemClockTo obtainLocalDateInstance:

    LocalDate localDate = SystemFactory.getClock().getLocalDate();

    You can also explicitly provide the values of each field to createLocalDate:

    LocalDate localDate = new LocalDate(2009, 9, 6);// September 6, 2009

    LocalDateReplacedYearMonthDay.

  • LocalTime: This class encapsulates a time in a day. When the geographical location is not important, you can use this class to store only a time in a day. For example, may be an important time in a day (for example, a Cron task will be started and it will back up a part of the file system ), however, this time is not specific to a specific day, so I do not need to know other information about this time point.

    Sample ApplicationSystemClockObtainLocalTimeFor example:

    LocalTime localTime = SystemFactory.getClock().getLocalTime();

    You can also explicitly provide the values of each field to createLocalTime:

    LocalTime localTime = new LocalTime(13, 30, 26, 0);// 1:30:26PM

Time Span

It is useful to know a specific time point or a local time segment, but it is also useful to express a time span. Joda provides three classes to simplify this process. You can select a class that represents different spans:

  • Duration: This class indicates an absolute precise span, in milliseconds. The method provided by this class can be used to pass the standard mathematical conversion (for example, 1 minute = 60 seconds, 1 day = 24 hours ), converts a time span to a standard unit (such as seconds, minutes, and hours ).

    You can only useDurationInstance: You want to convert a time span, but you do not care about the time span when it occurs, or it is convenient to use the millisecond processing time span.

  • Period: This class representsDurationThe same concept, but expressed in units that people are familiar with, such as year, month, and week.

    You can usePeriod: You are not concerned about when a single field must occur during this period, or you are more concerned about the ability to retrieve a single field. These fields are describedPeriodEncapsulation time span.

  • Interval: This class indicates a specific time span, which is defined by a specific time span.IntervalIsHalf-OpenRange, which indicates thatIntervalThe encapsulated time span includes the start time, but does not include the end time.

    It can be used in the following scenarios:Interval: A time span that starts and ends with a specific point in a consecutive interval.

Back to Top

Processing time in joda Mode

Now you know how to create some very useful joda classes. I will show you how to use them to perform date calculation. Then you will learn how joda can easily interoperate with JDK.

Date Calculation

If you only need to use placeholders for date/time information, JDK is fully competent, but it performs poorly in date/time calculation, which is joda's strength. I will show you some simple examples.

Suppose that I want to calculate the last day of the previous month under the current system date. For this example, I don't care about the time of the day, because I only need to get the year, month, and day, as shown in Listing 6:

Listing 6. Using joda to calculate a date

LocalDate now = SystemFactory.getClock().getLocalDate();LocalDate lastDayOfPreviousMonth =\  now.minusMonths(1).dayOfMonth().withMaximumValue(); 

 

You maydayOfMonth()Call interest. This is called in jodaProperty). It is equivalent to the property of a Java object. The attribute is named based on the common structure and is used to access this structure for computing purposes. Attribute is the key to achieving joda's computing power. All the four joda classes you have seen have these attributes. Some examples include:

  • yearOfCentury
  • dayOfYear
  • monthOfYear
  • dayOfMonth
  • dayOfWeek

I will introduce the example in Listing 6 in detail to show you the entire computing process. First, I subtract a month from the current month and get "last month ". Next, I requesteddayOfMonthIt gives me the last day of the month. Note that these calls are connected together (note jodaReadableInstantSub-classes are immutable). In this way, you only need to capture the results of the last method in the call chain to obtain the results of the entire calculation.

When the intermediate computing result is not important to me, I often use this computing mode. (I use JDK in the same wayBigDecimal). Suppose you want to get the date of the first Tuesday of the 11th month in any year, and the day must be after the first Monday of the month. Listing 7 shows how to complete this computation:

Listing 7. Calculate the first Tuesday after the first Monday in mid-December November

LocalDate now = SystemFactory.getClock().getLocalDate();LocalDate electionDate = now.monthOfYear() .setCopy(11)        // November .dayOfMonth()       // Access Day Of Month Property .withMinimumValue() // Get its minimum value .plusDays(6)        // Add 6 days .dayOfWeek()        // Access Day Of Week Property .setCopy("Monday")  // Set to Monday (it will round down) .plusDays(1);       // Gives us Tuesday

 

The annotations in listing 7 help you understand how the code gets results..setCopy("Monday")Is the Key to the entire computing. No matter the centerLocalDateIf the value isdayOfWeekSetting the attribute to Monday can always be rounded off. In this way, you can get the first Monday by adding 6 days at the beginning of each month. Add one day to get the first Tuesday. Joda makes it very easy to execute such calculations.

The following are some other Computation Tasks that become super simple due to the use of joda:

Run the following code to calculate the date after two weeks from now on:

DateTime now = SystemFactory.getClock().getDateTime();DateTime then = now.plusWeeks(2);

 

In this way, you can calculate the date after 90 days from tomorrow:

DateTime now = SystemFactory.getClock().getDateTime();DateTime tomorrow = now.plusDays(1);DateTime then = tomorrow.plusDays(90);

 

(Yes, I can alsonowWhat if we add 91 days ?)

The following is the calculation time after 156 seconds from now on:

DateTime now = SystemFactory.getClock().getDateTime();DateTime then = now.plusSeconds(156);

 

The following code calculates the last day of the second month after five years:

DateTime now = SystemFactory.getClock().getDateTime();DateTime then = now.minusYears(5) // five years ago               .monthOfYear()     // get monthOfYear property               .setCopy(2)        // set it to February               .dayOfMonth()      // get dayOfMonth property               .withMaximumValue();// the last day of the month

 

There are too many such examples. I already know how to calculate them. Try the sample application and experience how interesting it is to use joda to calculate any date.

JDK interoperability

Many of my codes use JDK.DateAndCalendarClass. But thanks to joda, I can execute any necessary date algorithms and switch back to the JDK class. This brings together the advantages of both. All the joda classes you see in this article can be viewed from the JDKCalendarOrDateCreate, as you can see in the create joda-time object. For the same reason, you can create a JDK from any joda class you have ever seen.CalendarOrDate.

Listing 8 showsReadableInstantHow easy it is to convert a subclass to a JDK class:

Listing 8. From jodaDateTimeClass to create a JDK class

DateTime dateTime = SystemFactory.getClock().getDateTime();Calendar calendar = dateTime.toCalendar(Locale.getDefault());Date date = dateTime.toDate();DateMidnight dateMidnight = SystemFactory.getClock()  .getDateMidnight();date = dateMidnight.toDate();

 

ForReadablePartialSubclass, as shown in listing 9:

Listing 9. Create a representationLocalDateOfDateObject

LocalDate localDate = SystemFactory.getClock().getLocalDate();Date date = localDate.toDateMidnight().toDate();

 

To createDateFromSystemClockObtained inLocalDate, You must first convert it toDateMidnightObject, then you only needDateMidnightObjectDate. (Of courseDateObject will set its own time part to midnight ).

JDK interoperability is built into the joda API, so you do not need to replace all your interfaces if they are bound to the JDK. For example, you can use joda to complete the complex section and then use the JDK processing interface.

Back to Top

Format the time in joda Mode

You can use JDK to format the date for printing, but I always think it should be simpler. This is another feature that the joda designer has improved. To Format a joda object, call itstoString()Method, and if you want to, pass a standard ISO-8601 or a JDK-compatible control string to tell JDK how to perform formatting. You do not need to create a separateSimpleDateFormatObject (but joda does provideDateTimeFormatterClass ). Call the joda object'stoString()Method. I will show some examples.

Listing 10 usesISODateTimeFormatStatic Method:

Listing 10. Using ISO-8601

DateTime dateTime = SystemFactory.getClock().getDateTime();dateTime.toString(ISODateTimeFormat.basicDateTime());dateTime.toString(ISODateTimeFormat.basicDateTimeNoMillis());dateTime.toString(ISODateTimeFormat.basicOrdinalDateTime());dateTime.toString(ISODateTimeFormat.basicWeekDateTime());

 

Four in listing 10toString()The following content is created for each call:

20090906T080000.000-050020090906T080000-05002009249T080000.000-05002009W367T080000.000-0500

 

You can also passSimpleDateFormatJDK-compatible format string, as shown in listing 11:

Listing 11. PassSimpleDateFormatString

DateTime dateTime = SystemFactory.getClock().getDateTime();dateTime.toString("MM/dd/yyyy hh:mm:ss.SSSa");dateTime.toString("dd-MM-yyyy HH:mm:ss");dateTime.toString("EEEE dd MMMM, yyyy HH:mm:ssa");dateTime.toString("MM/dd/yyyy HH:mm ZZZZ");dateTime.toString("MM/dd/yyyy HH:mm Z");09/06/2009 02:30:00.000PM06-Sep-2009 14:30:00Sunday 06 September, 2009 14:30:00PM09/06/2009 14:30 America/Chicago09/06/2009 14:30 -0500

 

View related information in javadocjoda.time.format.DateTimeFormatTo obtainSimpleDateFormatMore information about compatible format strings, and can be passed to the joda objecttoString()Method.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.