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(long companyId, Locale locale, TimeZone timeZone) {
45 _companyId = companyId;
46 _locale = locale;
47 _timeZone = timeZone;
48 _todayString = LanguageUtil.get(_companyId, _locale, "today");
49 _yesterdayString = LanguageUtil.get(_companyId, _locale, "yesterday");
50 }
51
52 public StringBuffer format(Date date, StringBuffer sb, FieldPosition pos) {
53 String dateString = StringPool.NBSP;
54
55 if (date != null) {
56 Date today = new Date();
57
58 Calendar cal = Calendar.getInstance(_timeZone, _locale);
59
60 cal.setTime(today);
61 cal.add(Calendar.DATE, -1);
62
63 Date yesterday = cal.getTime();
64
65 Format dateFormatDate = FastDateFormatFactoryUtil.getDate(
66 _locale, _timeZone);
67 Format dateFormatDateTime = FastDateFormatFactoryUtil.getDateTime(
68 _locale, _timeZone);
69 Format dateFormatTime = FastDateFormatFactoryUtil.getTime(
70 _locale, _timeZone);
71
72 dateString = dateFormatDate.format(date);
73
74 if (dateString.equals(dateFormatDate.format(today))) {
75 dateString =
76 _todayString + StringPool.SPACE +
77 dateFormatTime.format(date);
78 }
79 else if (dateString.equals(dateFormatDate.format(yesterday))) {
80 dateString =
81 _yesterdayString + StringPool.SPACE +
82 dateFormatTime.format(date);
83 }
84 else {
85 dateString = dateFormatDateTime.format(date);
86 }
87 }
88
89 return sb.append(dateString);
90 }
91
92 public Date parse(String source, ParsePosition pos) {
93 Format dateFormatDate = FastDateFormatFactoryUtil.getDate(
94 _locale, _timeZone);
95 DateFormat dateFormatDateTime = DateFormatFactoryUtil.getDateTime(
96 _locale, _timeZone);
97
98 Date today = new Date();
99
100 String dateString = source.substring(pos.getIndex());
101
102 if (dateString.startsWith(_todayString)) {
103 dateString.replaceFirst(_todayString, dateFormatDate.format(today));
104 }
105 else if (dateString.startsWith(_yesterdayString)) {
106 Calendar cal = Calendar.getInstance(_timeZone, _locale);
107
108 cal.setTime(today);
109 cal.add(Calendar.DATE, -1);
110
111 Date yesterday = cal.getTime();
112
113 dateString.replaceFirst(
114 _todayString, dateFormatDate.format(yesterday));
115 }
116
117 return dateFormatDateTime.parse(dateString, new ParsePosition(0));
118 }
119
120 private long _companyId;
121 private Locale _locale;
122 private TimeZone _timeZone;
123 private String _todayString;
124 private String _yesterdayString;
125
126 }