Java Cookbook
Format a time interval
Problem:
You want to format a span of time.
Solution:
As of version 4, icu4j contains a DateIntervalFormat class. This class makes it relatively easy to format an interval value. The format will automatically format as compactly as possible. For example: if the difference between the two dates is only a few hours and both dates occur on the same day, the year, month, and day parts of the date will be omitted.
In order to try this example out you will need to download a copy of icu4j from http://icu-project.org/download/4.0.html#ICU4J .
Import the correct classes
import java.text.FieldPosition;
import com.ibm.icu.text.DateFormat;
import com.ibm.icu.text.DateIntervalFormat;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.ULocale;
Then simply get an instance of the DateIntervalFormat class and format:
//Get two calendar instances
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = (Calendar)cal1.clone();
//increment one calendar by one week.
cal2.add(Calendar.HOUR, 4);
cal2.add(Calendar.MINUTE, 34);
//Get an instance of DateIntervalFormat. Specify the date format skeleton to use.
//The skeleton is an example format that will be used as a base for the interval format.
//You can specify your own skeleton format, or use one of the defaults in the DateFormat class
DateIntervalFormat dtIntervalFmt = DateIntervalFormat.getInstance(DateFormat.HOUR_MINUTE, new ULocale("ja"));
//Create a StringBuffer to hold the formatted value.
StringBuffer str = new StringBuffer("");
//Create a FieldPosition to specify the position for the StringBuffer
FieldPosition pos = new FieldPosition(0);
//format the interval. The formatted value is placed in the StringBuffer.
dtIntervalFmt.format(cal1, cal2, str, pos);
System.out.println(str);
Running this we get an output of "19時20分~23時54分".
If you are testing any of these recipes in Eclipse and the characters are not displaying correctly in your console visit http://i18ncookbook.com/eclipse_settings.
This site is ad supported. I hope you find something among our sponsors worth clicking. ;)
i18n search