Grails/Java new Date() different in GSP

白昼怎懂夜的黑 提交于 2019-12-25 05:46:18

问题


I'm running across something very strange. If i println new Date() in a controller the output is in UTC format (which is what I want). But when I print new Date() from a grails gsp the date is in EDT format and is off.

I'm running my app on CentOS Linux 6.5 through Tomcat 7. The system date and hardware date is using UTC.

Here is my Java version:

java version "1.7.0_51"
Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.51-b03, mixed mode)

I've tried adding:

TimeZone.setDefault(TimeZone.getTimeZone("UTC"))

To my bootstrap, but it still doesn't use UTC in the view.

Basically I want everything to use UTC but the only time it isn't is when I print new Date() from within a view.

Any thoughts?

EDIT:

I don't believe formatDate will work for me because I'm not actually just displaying the date for the user. I'm comparing the new Date() object to another date. I just printed the date to the response because I wanted to see why comparing the dates wasn't working. Here is the code snippet I'm using with the new Date() object:

<g:set var="dateNow" value="${new Date()}" />
<g:if test="${ticket.ticketEndDate.before(dateNow)}">
    <div>
        Ticket closed on ${ticket.ticketEndDate.format('EEE MMM dd, yyyy hh:mm a')}.
    </div>
</g:if>

回答1:


The time zone only affects how the Date is displayed when formatted to a String.

The Date object stores its value in milliseconds since January 1, 1970 UTC. And that value is used when comparing Dates.

You can test this by calling Date.getTime()

See this answer for a more detailed explanation: https://stackoverflow.com/a/308689/3855010




回答2:


You shouldn't use something like ${new Date()} in a GSP to render a Date to the response. You should use the <g:formatDate> tag and when you do that you get to specify a format string that represents specifically how you want the date formatted. See http://grails.org/doc/latest/ref/Tags/formatDate.html for examples and more details.



来源:https://stackoverflow.com/questions/24898020/grails-java-new-date-different-in-gsp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!