1
22
23 package com.liferay.portal.kernel.util;
24
25 import com.liferay.portal.kernel.language.LanguageUtil;
26
27 import java.text.DateFormat;
28 import java.text.FieldPosition;
29 import java.text.Format;
30 import java.text.ParsePosition;
31
32 import java.util.Calendar;
33 import java.util.Date;
34 import java.util.Locale;
35 import java.util.TimeZone;
36
37
42 public class PrettyDateFormat extends DateFormat {
43
44 public PrettyDateFormat(Locale locale, TimeZone timeZone) {
45 _locale = locale;
46 _timeZone = timeZone;
47 _todayString = LanguageUtil.get(_locale, "today");
48 _yesterdayString = LanguageUtil.get(_locale, "yesterday");
49 }
50
51
54 public PrettyDateFormat(long companyId, Locale locale, TimeZone timeZone) {
55 this(locale, timeZone);
56 }
57
58 public StringBuffer format(Date date, StringBuffer sb, FieldPosition pos) {
59 String dateString = StringPool.NBSP;
60
61 if (date != null) {
62 Date today = new Date();
63
64 Calendar cal = Calendar.getInstance(_timeZone, _locale);
65
66 cal.setTime(today);
67 cal.add(Calendar.DATE, -1);
68
69 Date yesterday = cal.getTime();
70
71 Format dateFormatDate = FastDateFormatFactoryUtil.getDate(
72 _locale, _timeZone);
73 Format dateFormatDateTime = FastDateFormatFactoryUtil.getDateTime(
74 _locale, _timeZone);
75 Format dateFormatTime = FastDateFormatFactoryUtil.getTime(
76 _locale, _timeZone);
77
78 dateString = dateFormatDate.format(date);
79
80 if (dateString.equals(dateFormatDate.format(today))) {
81 dateString =
82 _todayString + StringPool.SPACE +
83 dateFormatTime.format(date);
84 }
85 else if (dateString.equals(dateFormatDate.format(yesterday))) {
86 dateString =
87 _yesterdayString + StringPool.SPACE +
88 dateFormatTime.format(date);
89 }
90 else {
91 dateString = dateFormatDateTime.format(date);
92 }
93 }
94
95 return sb.append(dateString);
96 }
97
98 public Date parse(String source, ParsePosition pos) {
99 Format dateFormatDate = FastDateFormatFactoryUtil.getDate(
100 _locale, _timeZone);
101 DateFormat dateFormatDateTime = DateFormatFactoryUtil.getDateTime(
102 _locale, _timeZone);
103
104 Date today = new Date();
105
106 String dateString = source.substring(pos.getIndex());
107
108 if (dateString.startsWith(_todayString)) {
109 dateString.replaceFirst(_todayString, dateFormatDate.format(today));
110 }
111 else if (dateString.startsWith(_yesterdayString)) {
112 Calendar cal = Calendar.getInstance(_timeZone, _locale);
113
114 cal.setTime(today);
115 cal.add(Calendar.DATE, -1);
116
117 Date yesterday = cal.getTime();
118
119 dateString.replaceFirst(
120 _todayString, dateFormatDate.format(yesterday));
121 }
122
123 return dateFormatDateTime.parse(dateString, new ParsePosition(0));
124 }
125
126 private Locale _locale;
127 private TimeZone _timeZone;
128 private String _todayString;
129 private String _yesterdayString;
130
131 }