Format date in using DateTimeConverter

前端 未结 3 425
面向向阳花
面向向阳花 2021-01-24 19:22

I have a that has with CategoryHistory objects loaded in it. I only show the Date date

相关标签:
3条回答
  • 2021-01-24 19:54

    Example

    xhtml

    <h:selectOneMenu value="#{tbMonitoreoController.fechaMonitoreo}">
    <f:selectItems value="#{tbMonitoreoController.fechasMonitoreo}" />
    

    Method in tbMonitoreoController

    public SelectItem[] getFechasMonitoreo(){
        Collection<Date> entities = getEjbFacade().getFechasMonitoreo();
        return JsfUtil.getSelectItemsFechasMonitoreo(entities, true);
    }
    
    public static SelectItem[] getSelectItemsFechasMonitoreo(Collection<Date> listDate, boolean selectOne) {
        int size = selectOne ? (listDate.size() + 1) : listDate.size();
        SelectItem[] items = new SelectItem[size];
        int i = 0;
    
        if (selectOne) {
            items[0] = new SelectItem(null, "---");
            i++;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
        for (Date x : listDate) {
            items[i++] = new SelectItem(x, simpleDateFormat.format(x));
        }
        return items;
    }
    

    0 讨论(0)
  • 2021-01-24 20:04

    Unfortunately, the JSF converters only applies on the input value, not on the input label.

    You'll need to solve this other ways. E.g. a getter which uses SimpleDateFormat to format the date. Or if your environment supports EL 2.2, simply invoke the converter method directly (you've it as managed bean already):

    <f:selectItems value="#{admin.categoryHistories}" var="n" itemValue="#{n.id}" 
        itemLabel="#{dateAndTimeconverter.getAsString(facesContext, component, n.date)}">
    

    If you happen to use JSF utility library OmniFaces, then you can also use its of:formatDate() function. E.g.:

    <f:selectItems value="#{admin.categoryHistories}" var="n" itemValue="#{n.id}" 
        itemLabel="#{of:formatDate(n.date, 'd MMM yyyy')}">
    
    0 讨论(0)
  • 2021-01-24 20:17

    You can use a converter method in your bean, as:

    public class Admin{
        ...
            public String formatDate(Date fecha, String pattern) {
                return (new SimpleDateFormat(pattern)).format(fecha);
            }
        ...
    }
    

    And, in your xhtml page inside f:selectItems:

    <f:selectItems value="#{admin.categoryHistories}" var="n"
                   itemValue="#{n.id}" itemLabel="#{admin.formatDate(n.date,'d MMM yyyy')}">
    </f:selectItems>
    
    0 讨论(0)
提交回复
热议问题