001
014
015 package com.liferay.portal.kernel.util;
016
017 import com.liferay.portal.kernel.language.LanguageUtil;
018
019 import java.text.DateFormat;
020 import java.text.FieldPosition;
021 import java.text.Format;
022 import java.text.ParsePosition;
023
024 import java.util.Calendar;
025 import java.util.Date;
026 import java.util.Locale;
027 import java.util.TimeZone;
028
029
032 public class PrettyDateFormat extends DateFormat {
033
034 public PrettyDateFormat(Locale locale, TimeZone timeZone) {
035 _locale = locale;
036 _timeZone = timeZone;
037 _todayString = LanguageUtil.get(_locale, "today");
038 _yesterdayString = LanguageUtil.get(_locale, "yesterday");
039 }
040
041 @Override
042 public StringBuffer format(Date date, StringBuffer sb, FieldPosition pos) {
043 String dateString = StringPool.NBSP;
044
045 if (date == null) {
046 return sb.append(dateString);
047 }
048
049 Date today = new Date();
050
051 Calendar cal = Calendar.getInstance(_timeZone, _locale);
052
053 cal.setTime(today);
054 cal.add(Calendar.DATE, -1);
055
056 Date yesterday = cal.getTime();
057
058 Format dateFormatDate = FastDateFormatFactoryUtil.getDate(
059 _locale, _timeZone);
060 Format dateFormatDateTime = FastDateFormatFactoryUtil.getDateTime(
061 _locale, _timeZone);
062 Format dateFormatTime = FastDateFormatFactoryUtil.getTime(
063 _locale, _timeZone);
064
065 dateString = dateFormatDate.format(date);
066
067 if (dateString.equals(dateFormatDate.format(today))) {
068 dateString =
069 _todayString + StringPool.SPACE + dateFormatTime.format(date);
070 }
071 else if (dateString.equals(dateFormatDate.format(yesterday))) {
072 dateString =
073 _yesterdayString + StringPool.SPACE +
074 dateFormatTime.format(date);
075 }
076 else {
077 dateString = dateFormatDateTime.format(date);
078 }
079
080 return sb.append(dateString);
081 }
082
083 @Override
084 public Date parse(String source, ParsePosition pos) {
085 Format dateFormatDate = FastDateFormatFactoryUtil.getDate(
086 _locale, _timeZone);
087 DateFormat dateFormatDateTime = DateFormatFactoryUtil.getDateTime(
088 _locale, _timeZone);
089
090 Date today = new Date();
091
092 String dateString = source.substring(pos.getIndex());
093
094 if (dateString.startsWith(_todayString)) {
095 dateString = dateString.replaceFirst(
096 _todayString, dateFormatDate.format(today));
097 }
098 else if (dateString.startsWith(_yesterdayString)) {
099 Calendar cal = Calendar.getInstance(_timeZone, _locale);
100
101 cal.setTime(today);
102 cal.add(Calendar.DATE, -1);
103
104 Date yesterday = cal.getTime();
105
106 dateString = dateString.replaceFirst(
107 _todayString, dateFormatDate.format(yesterday));
108 }
109
110 return dateFormatDateTime.parse(dateString, new ParsePosition(0));
111 }
112
113 private final Locale _locale;
114 private final TimeZone _timeZone;
115 private final String _todayString;
116 private final String _yesterdayString;
117
118 }