如何用Java格式化日期范围? [英] How do you format a date range in Java?
问题描述
我有两个日期-开始和结束。我想对它们进行格式化,以便在月份匹配的情况下将其折叠为类似 20-23 AUG的格式,而在月份结束时仍可以正确格式化,例如 20 SEP-1 OCT。
I have two dates - a start and an end. I'd like to format them so that if the months match, they collapse to something like "20-23 AUG" and still format correctly if they break over the end of the month, like "20 SEP - 1 OCT". Are there any libraries out there for accomplishing this, or would I have to hand code rules for displaying ranges of dates using individual DateFormats?
推荐答案
我对其他答案感到失望。 Joda time在GWT中无效,SimpleDateFormat也无效。无论如何,我已经知道GWT中的DateTimeFormat。主要问题是不建议使用日期对象的getMonth()函数,因此似乎没有比较月和/或年的好方法。此解决方案不包括年份检查(可以通过更改monthFormatter轻松添加),但这对我的情况并不重要。
I was disappointed with the other answers. Joda time didn't work in GWT and neither does SimpleDateFormat. Anyway, I already knew about DateTimeFormat in GWT. The main issue is that date objects getMonth() function is deprecated, and there doesn't seem to be a good way to compare months and/or years. This solution doesn't include year checking (which could be easily added by changing the monthFormatter), but that's not important for my case.
public final class DateUtility
{
public static final DateTimeFormat MONTH_FORMAT = DateTimeFormat.getFormat("MMM");
public static final DateTimeFormat DAY_FORMAT = DateTimeFormat.getFormat("dd");
public static final DateTimeFormat DAY_MONTH_FORMAT = DateTimeFormat.getFormat("dd MMM");
public static final String DASH = " - ";
/**
* Returns a "collapsed" date range String representing the period of time
* between two Date parameters. Example: August 19 as a {@code startDate}
* and August 30 as an {@code endDate} will return "19 - 30 AUG", August 28
* as a {@code startDate} and September 7 as an {@code endDate} will return
* "28 AUG - 07 SEP". This means if you pass this two dates which cannot
* collapse into a shorter form, then the longer form is returned. Years
* are ignored, and the start and end dates are not checked to ensure we
* are not going backwards in time (Aug 10 - July 04 is not checked).
*
* @param startDate
* the start Date in the range.
* @param endDate
* the end Date in the range.
* @return a String representation of the range between the two dates given.
*/
public static String collapseDate(Date startDate, Date endDate) {
String formattedDateRange;
// Get a comparison result to determine if the Months are the same
String startDateMonth = MONTH_FORMAT.format(startDate);
String endDateMonth = MONTH_FORMAT.format(endDate);
if (startDateMonth.equals(endDateMonth))
{
formattedDateRange = DAY_FORMAT.format(startDate) + DASH
+ DAY_MONTH_FORMAT.format(endDate).toUpperCase();
}
else
{
// Months don't match, split the string across both months
formattedDateRange = DAY_MONTH_FORMAT.format(startDate).toUpperCase()
+ DASH + DAY_MONTH_FORMAT.format(endDate).toUpperCase();
}
return formattedDateRange;
}
}
这篇关于如何用Java格式化日期范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!