格式化日期并使用JSTL和EL显示日期 [英] Format a date and display it using JSTL and EL

查看:257
本文介绍了格式化日期并使用JSTL和EL显示日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在JSP中格式化和显示Date对象,最好使用JSTL和EL,但欢迎使用其他任何解决方案?我无法更改bean对象.

How do I format and display a Date object in a JSP, most preferably using JSTL and EL but any other solution is welcome? I can not change the bean object.

我有以下课程:

import java.util.Date;
public class Person {
    private Date myDate; 
    public Date getMyDate() {
        return myDate;
    }
    public void setMyDate(Date myDate){
        this.myDate = myDate;
    }
}

我正在尝试在JSP页面中的该对象中显示日期.当我执行此<c:out value="${person.myDate} />时,它将在页面中打印出来. 2013-06-08 00:00:00.0

I am trying to display the date in this object in a JSP page. When I do this <c:out value="${person.myDate} /> it prints this in the page. 2013-06-08 00:00:00.0

我要做的是删除日期的时间部分并将其格式化为MM-dd-yyyy.

What I want to do is remove the time portion of the date and format it to MM-dd-yyyy.

我尝试过:

<c:set var="myDate" value="${person.myDate }"/>
<fmt:formatDate value="${myDate}" type="date" var="formattedDate"/>

它给了我以下错误

无法将字符串'$ {myDate}'转换为属性值java.lang.IllegalArgumentException的类java.util.Date:属性编辑器未在PropertyEditorManager中注册

Unable to convert string '${myDate}' to class java.util.Date for attribute value: java.lang.IllegalArgumentException: Property Editor not registered with the PropertyEditorManager

然后我尝试了以下操作:

Then I tried the following:

<c:set var="myDate" value="${person.myDate }"/>
<fmt:parseDate value="${myDate }" var="parsedDate" pattern="MM-dd-yyyy"/>
<c:out value="${parsedDate }"/>

然后我得到了

不可解析的日期:"$ {myDate}"

Unparseable date: "${myDate }"

推荐答案

您的代码通常应该可以正常工作.尝试这样:

Your code should normally work. Try like this:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<fmt:formatDate value="${person.myDate}" var="formattedDate" 
                type="date" pattern="MM-dd-yyyy" />
${formattedDate}

如果您使用错误的JSTL声明来匹配Servlet/JSP版本,则通常不起作用.确保在尝试任何其他操作之前先阅读以下内容:

It usually doesn't work if you have wrong JSTL declarations to match your Servlet/JSP version. Make sure you read this before trying anything else: How to Reference and Use JSTL in your Web Application.

如果您不完全了解您的环境,请可以执行一些测试以找出版本,尽管用JSP编写的简单${1 + 2}应该可以很好地说明JSP的版本.如果在浏览器中看到3,则说明您正在使用JSP 2.x,如果看到字符串${1 + 2}则说明您在JSP 1.x上.

If you don't know exactly your environment, you can perform some tests to find out the versions although a simple ${1 + 2} written in your JSP should be a good indicator of the JSP version. If you see 3 in your browser then you are using JSP 2.x, if you see the string ${1 + 2} instead then you are on JSP 1.x.

这篇关于格式化日期并使用JSTL和EL显示日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆