2

I'm using Spring's @DateTimeFormat annotation, with a custom pattern, on the field of an object which is passed in via an HTTP POST endpoint. The particular field is set on the front end UI with a javascript widget which always uses the 'en_us' locale. However, if the browser is set to a locale other than 'en_us' then the parsing of the date/time may fail on the backend because the @DateTimeFormat uses the browser (or HTTP header) locale instead of 'en_us'.

Is there anyway to force the DateTimeFormat annotation to use the 'en_us' locale?

I realize the DateTimeFormat is doing what makes sense by using the HTTP header locale. However, since I control the front end, and for the time being don't want to change the front end javascript widget, I'm wondering if there is a way to set the locale of DateTimeFormat.

binarylegit
  • 319
  • 1
  • 4
  • 15

1 Answers1

0

Is it necessary to use a custom date format? In general it is better to have an agnostic date format, e.g. use something like ISO date format with timezone added which is international or less preferred use the milliseconds from UTC. That way you do not have to worry about these details. If absolutely necessary things to use would be:

  1. The pattern attribute to set a fixed pattern, here for the region en_us

  2. A Spring filter (not verified, pseudo code):

@Component
public class MyDateFilter implements Filter {

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest incoming = (HttpServletRequest) request;
    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(incoming) {

      public String getHeader(String name) {
        if (<HTTP header locale>.equals(name)) {
          return TODO;
        }
        return super.getHeader(name);
      }
    };
    chain.doFilter(wrapper, response);
  }

}
k_o_
  • 5,143
  • 1
  • 34
  • 43