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
044 public PrettyDateFormat(long companyId, Locale locale, TimeZone timeZone) {
045 this(locale, timeZone);
046 }
047
048 @Override
049 public StringBuffer format(Date date, StringBuffer sb, FieldPosition pos) {
050 String dateString = StringPool.NBSP;
051
052 if (date != null) {
053 Date today = new Date();
054
055 Calendar cal = Calendar.getInstance(_timeZone, _locale);
056
057 cal.setTime(today);
058 cal.add(Calendar.DATE, -1);
059
060 Date yesterday = cal.getTime();
061
062 Format dateFormatDate = FastDateFormatFactoryUtil.getDate(
063 _locale, _timeZone);
064 Format dateFormatDateTime = FastDateFormatFactoryUtil.getDateTime(
065 _locale, _timeZone);
066 Format dateFormatTime = FastDateFormatFactoryUtil.getTime(
067 _locale, _timeZone);
068
069 dateString = dateFormatDate.format(date);
070
071 if (dateString.equals(dateFormatDate.format(today))) {
072 dateString =
073 _todayString + StringPool.SPACE +
074 dateFormatTime.format(date);
075 }
076 else if (dateString.equals(dateFormatDate.format(yesterday))) {
077 dateString =
078 _yesterdayString + StringPool.SPACE +
079 dateFormatTime.format(date);
080 }
081 else {
082 dateString = dateFormatDateTime.format(date);
083 }
084 }
085
086 return sb.append(dateString);
087 }
088
089 @Override
090 public Date parse(String source, ParsePosition pos) {
091 Format dateFormatDate = FastDateFormatFactoryUtil.getDate(
092 _locale, _timeZone);
093 DateFormat dateFormatDateTime = DateFormatFactoryUtil.getDateTime(
094 _locale, _timeZone);
095
096 Date today = new Date();
097
098 String dateString = source.substring(pos.getIndex());
099
100 if (dateString.startsWith(_todayString)) {
101 dateString = dateString.replaceFirst(
102 _todayString, dateFormatDate.format(today));
103 }
104 else if (dateString.startsWith(_yesterdayString)) {
105 Calendar cal = Calendar.getInstance(_timeZone, _locale);
106
107 cal.setTime(today);
108 cal.add(Calendar.DATE, -1);
109
110 Date yesterday = cal.getTime();
111
112 dateString = dateString.replaceFirst(
113 _todayString, dateFormatDate.format(yesterday));
114 }
115
116 return dateFormatDateTime.parse(dateString, new ParsePosition(0));
117 }
118
119 private Locale _locale;
120 private TimeZone _timeZone;
121 private String _todayString;
122 private String _yesterdayString;
123
124 }