2

I have a spring-boot application with a controller that handles some requests with a date passed as a query parameter. E.g URI for request:

http://localhost:8081/test/read?from=2018-01-01T00:00:00Z

However, using the @RequestParam annotation to parse the date from the URI, I am getting a date in the local timezone, not the UTC timezone (as indicated by the 'Z').

I've tried setting the jdbctemplate time zone, the java.util.timezone and the spring.jackson.time_zone in application.properties, but that didn't help.

@RequestMapping(value = "test/read", method = RequestMethod.GET)
    public ResponseEntity<String> get(
            @RequestParam(value="from") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'") final Date from)
    // value of date in 'from' is in local timezone

The value should be in the UTC timezone, due to the trailing 'Z' in the pattern passed to @DateTimeFormat.

Any ideas for what I'm missing here?

jateeq
  • 55
  • 1
  • 6
  • Possible duplicate of [Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST](https://stackoverflow.com/questions/19112357/java-simpledateformatyyyy-mm-ddthhmmssz-gives-timezone-as-ist) – 1615903 May 14 '19 at 09:05
  • 1
    A `java.util.Date` doesn't have a time zone, it is a wrapper around a long with the number of milliseconds since 1-1-1970 00:00 UTC. Its default `toString()` will render the value in the default JVM time zone. You may want to consider switching to the `java.time` classes instead. – Mark Rotteveel May 14 '19 at 09:39

1 Answers1

3

When you start your application, the VM automatically inherits the default timezone of your local machine. You can update the default timezone for your application as following.

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

        SpringApplication.run(Application.class, args);
    }

}
Mr.J4mes
  • 9,168
  • 9
  • 48
  • 90
  • 3
    This is a workaround - the actual problem is the date pattern that has a constant `'Z'` instead of timezone identifier, so the timezone is ignored. – 1615903 May 14 '19 at 09:06
  • @1615903: I do NOT consider this a workaround. In my projects, we deliberately set the default timezone to guarantee all date-related information are saved into the database in the same timezone. Otherwise, when we deploy microservices in different VM in different zones, it may come with different timezone if the OS is configured to automatically get the timezone from IP. – Mr.J4mes May 14 '19 at 09:11
  • The problem OP describes is that timezone is ignored from the parameter. Your solution is to set the default timezone to UTC. The timezone is still ignored from the parameter, but because it happens to be the same as the new default, it now works. That's why I consider this to be a workaround. – 1615903 May 14 '19 at 09:32