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