0

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>
sean3838
  • 65
  • 8
  • Are you actually using "print" or g:formatDate? If the latter, there's a way to pass a timezone in: http://grails.org/doc/latest/ref/Tags/formatDate.html – billjamesdev Jul 22 '14 at 21:37
  • I'm just using ${new Date()} to show the date in the view. The problem is I'm comparing the new date object (within the view) to another date that's in UTC format. – sean3838 Jul 22 '14 at 22:27
  • @MattJohnson this is not a duplicate of http://stackoverflow.com/questions/12208305/grails-saves-datetime-as-utc-time-but-reads-it-as-local-server-time. – Jeff Scott Brown Jul 23 '14 at 02:18

2 Answers2

4

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.

Jeff Scott Brown
  • 26,804
  • 2
  • 30
  • 47
  • The edit you have made turned this into a completely different question. The first question was about date formats and the second is about the actual value of the date. – Jeff Scott Brown Jul 23 '14 at 13:52
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

Community
  • 1
  • 1
MattZ
  • 266
  • 1
  • 6