How do I format a date range in Java?

I have two appointments - start and end I want to format them so that when the month matches, they will crash to a state similar to "20-23 Aug", and if they break through at the end of the month, they can still be formatted correctly, such as "20 Sep – 1 OCT" Is there any library available to do this, or do I have to use separate dateformats to handle code rules that display date ranges?

Solution

This is a solution using jodatime, which is the best library for handling Java dates (I checked last time) Formatting is simple, and using a custom dateformatter implementation can undoubtedly be improved This also checks for the same year, but does not output the year, which can be confusing

import org.joda.time.DateTime;

public class DateFormatterTest {

    public static void main(String[] args) {

        DateTime august23rd = new DateTime(2010,8,23,0);
        DateTime august25th = new DateTime(2010,25,0);
        DateTime september5th = new DateTime(2010,9,5,0);

        DateFormatterTest tester = new DateFormattertest();
        tester.outputDate(august23rd,august25th);
        tester.outputDate(august23rd,september5th);

    }

    private void outputDate(DateTime firstDate,DateTime secondDate) {
        if ((firstDate.getMonthOfYear() == secondDate.getMonthOfYear()) && (firstDate.getYear() == secondDate.getYear())) {
            System.out.println(firstDate.getDayOfMonth() + " - " + secondDate.getDayOfMonth() + " " + firstDate.monthOfYear().getAsShortText());
        } else {
            System.out.println(firstDate.getDayOfMonth() + " " + firstDate.monthOfYear().getAsShortText() + " - " + secondDate.getDayOfMonth() + " " + secondDate.monthOfYear().getAsShortText());
        }
    }
}

Output:

August 23rd to 25th

23 August to 5 September

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>