我恰好使用pretty time 1.0.6以人類可讀格式顯示兩個時間點之間的時間間隔。使用漂亮的時間庫在JSF中以人們可讀的格式顯示時間
有一個內置的JSF轉換,
com.ocpsoft.pretty.time.web.jsf.PrettyTimeConverter
,但它僅支持java.util.Date
對象。
我碰巧使用下面的轉換器,用於org.joda.time.DateTime
@ManagedBean
@ApplicationScoped
public final class PrettyJodaTimeConverter extends PrettyTimeConverter
{
@Override
public String getAsString(final FacesContext context, final UIComponent component, final Object value)
{
if (value instanceof DateTime) {
return super.getAsString(context, component, ((DateTime) value).toDate());
} else {
return super.getAsString(context, component, value);
}
}
}
此,「4小時前」上<h:outputText>
顯示的時間間隔,例如,例如
<h:outputText value="#{productInquiryManagedBean.lastInquiry}"
converter="#{prettyJodaTimeConverter}"/>
但是我需要顯示根據JSF託管bean中的條件檢查在<p:growl>
(或<p:messages>
,<h:messages>
)上發送消息。因此,此轉換器不能使用(請建議,如果它可以使用)。相反,我需要手動格式化在託管bean中的問題,像這樣,
private DateTime lastInquiry;
private String emailId;
private Product product;
if(productInquiryService.isPeriodExpired(30, emailId, product))
{
lastInquiry=productInquiryService.getDateTimeOfLastInquiry(email, product);
Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
PrettyTime time=new PrettyTime(lastInquiry.toDate(), locale);
time.setLocale(locale);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, Utility.getMessage("faces.message.error"), Utility.getMessage("inquiry.min.time.expire", time.format(new Date()))));
}
這將顯示一條消息上<p:growl>
像 - 「您所進行的調查,從4小時現在」。
是否可以將此消息格式更改爲「您作了詢問4小時前」與上面顯示的<h:outputText>
完全相同?
此外,此處顯示的間隔格式未本地化爲資源束中的特定位置。它似乎總是使用其默認語言環境。 PrettyTime#format()
生成的消息應該進行本地化。
我錯誤的參數傳遞給構造函數。因此錯誤的信息表明未來的時間。他們應該如下所示。
PrettyTime time=new PrettyTime(new Date(), locale);
time.format(lastInquiry.toDate());
//lastInquiry is fetched from the database which a customer made an inquiry on.
它現在顯示正確的(過去的時間)格式,如「4小時前」。
關於我一直在尋找的語言環境是HI
(實際上hi_IN
,印地文在印度)是不是在,即使它是在i18n and multiple-languages support節中提到那裏的圖書館提供的資源包(在com.ocpsoft.pretty.time.i18n
包)提供。
一個解決方法,你可以在javascript中做到這一點,使用轉換器做一個inputHidden,在onchange上註冊,當它改變時,給數據的咆哮提供值並顯示它。 –