1
22
23 package com.liferay.portal.util;
24
25 import com.liferay.portal.kernel.language.LanguageUtil;
26 import com.liferay.portal.kernel.util.StringPool;
27
28 import java.text.DateFormat;
29 import java.text.FieldPosition;
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
43 public class PrettyDateFormat extends DateFormat {
44
45 public PrettyDateFormat(long companyId, Locale locale, TimeZone timeZone) {
46 _companyId = companyId;
47 _locale = locale;
48 _timeZone = timeZone;
49 _todayString = LanguageUtil.get(_companyId, _locale, "today");
50 _yesterdayString = LanguageUtil.get(_companyId, _locale, "yesterday");
51 }
52
53 public StringBuffer format(Date date, StringBuffer sb, FieldPosition pos) {
54 String dateString = StringPool.NBSP;
55
56 if (date != null) {
57 Date today = new Date();
58
59 Calendar cal = Calendar.getInstance(_timeZone, _locale);
60
61 cal.setTime(today);
62 cal.add(Calendar.DATE, -1);
63
64 Date yesterday = cal.getTime();
65
66 DateFormat dateFormatDate = DateFormats.getDate(_locale, _timeZone);
67 DateFormat dateFormatDateTime =
68 DateFormats.getDateTime(_locale, _timeZone);
69 DateFormat dateFormatTime = DateFormats.getTime(_locale, _timeZone);
70
71 dateString = dateFormatDate.format(date);
72
73 if (dateString.equals(dateFormatDate.format(today))) {
74 dateString =
75 _todayString + StringPool.SPACE +
76 dateFormatTime.format(date);
77 }
78 else if (dateString.equals(dateFormatDate.format(yesterday))) {
79 dateString =
80 _yesterdayString + StringPool.SPACE +
81 dateFormatTime.format(date);
82 }
83 else {
84 dateString = dateFormatDateTime.format(date);
85 }
86 }
87
88 return sb.append(dateString);
89 }
90
91 public Date parse(String source, ParsePosition pos) {
92 DateFormat dateFormatDate = DateFormats.getDate(_locale, _timeZone);
93
94 DateFormat dateFormatDateTime =
95 DateFormats.getDateTime(_locale, _timeZone);
96
97 Date today = new Date();
98
99 String dateString = source.substring(pos.getIndex());
100
101 if (dateString.startsWith(_todayString)) {
102 dateString.replaceFirst(_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.replaceFirst(
113 _todayString, dateFormatDate.format(yesterday));
114 }
115
116 return dateFormatDateTime.parse(dateString, new ParsePosition(0));
117 }
118
119 private long _companyId;
120 private Locale _locale;
121 private TimeZone _timeZone;
122 private String _todayString;
123 private String _yesterdayString;
124
125 }