1
14
15 package com.liferay.portal.kernel.util;
16
17 import com.liferay.portal.kernel.language.LanguageUtil;
18
19 import java.text.DateFormat;
20 import java.text.FieldPosition;
21 import java.text.Format;
22 import java.text.ParsePosition;
23
24 import java.util.Calendar;
25 import java.util.Date;
26 import java.util.Locale;
27 import java.util.TimeZone;
28
29
34 public class PrettyDateFormat extends DateFormat {
35
36 public PrettyDateFormat(Locale locale, TimeZone timeZone) {
37 _locale = locale;
38 _timeZone = timeZone;
39 _todayString = LanguageUtil.get(_locale, "today");
40 _yesterdayString = LanguageUtil.get(_locale, "yesterday");
41 }
42
43
46 public PrettyDateFormat(long companyId, Locale locale, TimeZone timeZone) {
47 this(locale, timeZone);
48 }
49
50 public StringBuffer format(Date date, StringBuffer sb, FieldPosition pos) {
51 String dateString = StringPool.NBSP;
52
53 if (date != null) {
54 Date today = new Date();
55
56 Calendar cal = Calendar.getInstance(_timeZone, _locale);
57
58 cal.setTime(today);
59 cal.add(Calendar.DATE, -1);
60
61 Date yesterday = cal.getTime();
62
63 Format dateFormatDate = FastDateFormatFactoryUtil.getDate(
64 _locale, _timeZone);
65 Format dateFormatDateTime = FastDateFormatFactoryUtil.getDateTime(
66 _locale, _timeZone);
67 Format dateFormatTime = FastDateFormatFactoryUtil.getTime(
68 _locale, _timeZone);
69
70 dateString = dateFormatDate.format(date);
71
72 if (dateString.equals(dateFormatDate.format(today))) {
73 dateString =
74 _todayString + StringPool.SPACE +
75 dateFormatTime.format(date);
76 }
77 else if (dateString.equals(dateFormatDate.format(yesterday))) {
78 dateString =
79 _yesterdayString + StringPool.SPACE +
80 dateFormatTime.format(date);
81 }
82 else {
83 dateString = dateFormatDateTime.format(date);
84 }
85 }
86
87 return sb.append(dateString);
88 }
89
90 public Date parse(String source, ParsePosition pos) {
91 Format dateFormatDate = FastDateFormatFactoryUtil.getDate(
92 _locale, _timeZone);
93 DateFormat dateFormatDateTime = DateFormatFactoryUtil.getDateTime(
94 _locale, _timeZone);
95
96 Date today = new Date();
97
98 String dateString = source.substring(pos.getIndex());
99
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 }