Java 使用 JSTL 将长时间戳格式化为日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/75489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Formatting a long timestamp into a Date with JSTL
提问by scubabbl
I am pulling a long timestamp from a database, but want to present it as a Date using Tags only, no embedded java in the JSP.
I've created my own tag to do this because I was unable to get the parseDate and formatDate tags to work, but that's not to say they don't work.
Any advice?
我正在从数据库中提取一个很长的时间戳,但想仅使用标签将其显示为日期,而不是在 JSP 中嵌入 Java。
我创建了自己的标签来执行此操作,因为我无法使 parseDate 和 formatDate 标签起作用,但这并不是说它们不起作用。
有什么建议吗?
Thanks.
谢谢。
采纳答案by ScArcher2
The parseDate and formatDate tags work, but they work with Date objects. You can call new java.util.Date(longvalue) to get a date object, then pass that to the standard tag.
parseDate 和 formatDate 标签有效,但它们与 Date 对象一起使用。您可以调用 new java.util.Date(longvalue) 来获取日期对象,然后将其传递给标准标记。
somewhere other than the jsp create your date object.
jsp 以外的地方创建您的日期对象。
long longvalue = ...;//from database.
java.util.Date dateValue = new java.util.Date(longvalue);
request.setAttribute("dateValue", dateValue);
put it on the request and then you can access it in your tag like this.
把它放在请求上,然后你可以像这样在你的标签中访问它。
<fmt:formatDate value="${dateValue}" pattern="MM/dd/yyyy HH:mm"/>
回答by BenM
You can avoid having to make any changes to your Servlet by creating a date object within the JSP using the jsp:useBean
and jsp:setProperty
tags to set the time of newly created date object to that of the time stamp. For example:
通过使用jsp:useBean
和jsp:setProperty
标记在 JSP 内创建日期对象将新创建的日期对象的时间设置为时间戳的时间,您可以避免对 Servlet 进行任何更改。例如:
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<jsp:useBean id="dateValue" class="java.util.Date"/>
<jsp:setProperty name="dateValue" property="time" value="${timestampValue}"/>
<fmt:formatDate value="${dateValue}" pattern="MM/dd/yyyy HH:mm"/>