You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DesignDateConverter.java 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * Copyright 2000-2016 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.ui.declarative.converters;
  17. import java.text.ParseException;
  18. import java.text.SimpleDateFormat;
  19. import java.util.Date;
  20. import java.util.Locale;
  21. import com.vaadin.data.Result;
  22. import com.vaadin.data.util.converter.Converter;
  23. import com.vaadin.ui.declarative.DesignAttributeHandler;
  24. /**
  25. * A date converter to be used by {@link DesignAttributeHandler}. Provides
  26. * ISO-compliant way of storing date and time.
  27. *
  28. * @since 7.4
  29. * @author Vaadin Ltd
  30. */
  31. public class DesignDateConverter implements Converter<String, Date> {
  32. @Override
  33. public Result<Date> convertToModel(String value, Locale locale) {
  34. for (String pattern : new String[] { "yyyy-MM-dd HH:mm:ssZ",
  35. "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd HH",
  36. "yyyy-MM-dd", "yyyy-MM", "yyyy" }) {
  37. try {
  38. return Result.ok(new SimpleDateFormat(pattern).parse(value));
  39. } catch (ParseException e) {
  40. // not parseable, ignore and try another format
  41. }
  42. }
  43. return Result.error("Could not parse date value: " + value);
  44. }
  45. @Override
  46. public String convertToPresentation(Date value, Locale locale) {
  47. return new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ").format(value);
  48. }
  49. }