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.ParsePosition;
30
31 import java.util.Calendar;
32 import java.util.Date;
33 import java.util.Locale;
34 import java.util.TimeZone;
35
36
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 DateFormat dateFormatDate = DateFormats.getDate(_locale, _timeZone);
66 DateFormat dateFormatDateTime = DateFormats.getDateTime(
67 _locale, _timeZone);
68 DateFormat dateFormatTime = DateFormats.getTime(_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 DateFormat dateFormatDate = DateFormats.getDate(_locale, _timeZone);
92
93 DateFormat dateFormatDateTime =
94 DateFormats.getDateTime(_locale, _timeZone);
95
96 Date today = new Date();
97
98 String dateString = source.substring(pos.getIndex());
99
100 if (dateString.startsWith(_todayString)) {
101 dateString.replaceFirst(_todayString, dateFormatDate.format(today));
102 }
103 else if (dateString.startsWith(_yesterdayString)) {
104 Calendar cal = Calendar.getInstance(_timeZone, _locale);
105
106 cal.setTime(today);
107 cal.add(Calendar.DATE, -1);
108
109 Date yesterday = cal.getTime();
110
111 dateString.replaceFirst(
112 _todayString, dateFormatDate.format(yesterday));
113 }
114
115 return dateFormatDateTime.parse(dateString, new ParsePosition(0));
116 }
117
118 private long _companyId;
119 private Locale _locale;
120 private TimeZone _timeZone;
121 private String _todayString;
122 private String _yesterdayString;
123
124 }