JSP日期解析异常求助:无法解析Sat Mar 03 14:02:30 GMT 2018
Hey there! Let's troubleshoot why your date parsing is failing in JSP even though it worked perfectly in your Servlet. I've dealt with exactly this kind of issue before, so here are the most common fixes to try out:
The EEE (day name) and MMM (month abbreviation) parts of your pattern rely on an English locale, but JSP's <fmt:parseDate> tag defaults to your server's system locale (which might not be English). That's why your Servlet code worked—you probably explicitly set the locale there with Locale.ENGLISH when creating your SimpleDateFormat.
Add the locale attribute to your fmt:parseDate tag to replicate that behavior:
<fmt:parseDate value="Sat Mar 03 14:02:30 GMT 2018" pattern="EEE MMM dd HH:mm:ss z yyyy" var="parsedDate" locale="en_US"/>
You can test if this works by outputting the parsed date with:
<fmt:formatDate value="${parsedDate}" pattern="yyyy-MM-dd HH:mm:ss"/>
Even though your date string includes GMT, the parser might not always pick up the timezone correctly without a nudge. Add the timeZone attribute to be safe:
<fmt:parseDate value="Sat Mar 03 14:02:30 GMT 2018" pattern="EEE MMM dd HH:mm:ss z yyyy" var="parsedDate" locale="en_US" timeZone="GMT"/>
Make sure you have the correct taglib directives at the very top of your JSP—missing or misspelled imports can cause silent failures:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
When you use the var attribute in <fmt:parseDate>, the parsed date is stored in page scope by default. If you're trying to access it outside the current page (like in a included fragment), you might need to specify a broader scope:
<fmt:parseDate value="Sat Mar 03 14:02:30 GMT 2018" pattern="EEE MMM dd HH:mm:ss z yyyy" var="parsedDate" locale="en_US" scope="request"/>
Start with the locale fix—nine times out of ten, that's the reason the parsing breaks when moving from Servlet to JSP. If it still doesn't work, let me know what error messages you're seeing (if any) and we can dig deeper!
内容的提问来源于stack exchange,提问作者Genaut

