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.

DesignLocalDateTimeConverter.java 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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.time.LocalDate;
  18. import java.time.LocalDateTime;
  19. import java.time.format.DateTimeFormatter;
  20. import java.time.format.DateTimeParseException;
  21. import java.util.Locale;
  22. import com.vaadin.data.Converter;
  23. import com.vaadin.data.Result;
  24. import com.vaadin.data.ValueContext;
  25. import com.vaadin.ui.declarative.DesignAttributeHandler;
  26. /**
  27. * A {@link LocalDate} converter to be used by {@link DesignAttributeHandler}.
  28. * Provides ISO-compliant way of storing date and time.
  29. *
  30. * @since 8.0
  31. * @author Vaadin Ltd
  32. */
  33. public class DesignLocalDateTimeConverter
  34. implements Converter<String, LocalDateTime> {
  35. @Override
  36. public Result<LocalDateTime> convertToModel(String value,
  37. ValueContext context) {
  38. for (String pattern : new String[] { "yyyy-MM-dd HH:mm:ssZ",
  39. "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd HH",
  40. "yyyy-MM-dd", "yyyy-MM", "yyyy" }) {
  41. try {
  42. Locale effectiveLocale = context.getLocale()
  43. .orElse(Locale.ENGLISH);
  44. LocalDateTime date = DateTimeFormatter
  45. .ofPattern(pattern, effectiveLocale)
  46. .parse(value, LocalDateTime::from);
  47. return Result.ok(date);
  48. } catch (DateTimeParseException ignored) {
  49. // not parseable, ignore and try another format
  50. }
  51. }
  52. return Result.error("Could not parse date value: " + value);
  53. }
  54. @Override
  55. public String convertToPresentation(LocalDateTime value,
  56. ValueContext context) {
  57. return DateTimeFormatter
  58. .ofPattern("yyyy-MM-dd HH:mm:ss",
  59. context.getLocale().orElse(Locale.ENGLISH))
  60. .format(value);
  61. }
  62. }