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.

LocalDateTimeToDateConverter.java 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright 2000-2018 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.data.converter;
  17. import java.time.Instant;
  18. import java.time.LocalDateTime;
  19. import java.time.ZoneId;
  20. import java.util.Date;
  21. import java.util.Objects;
  22. import com.vaadin.data.Converter;
  23. import com.vaadin.data.Result;
  24. import com.vaadin.data.ValueContext;
  25. import com.vaadin.ui.DateTimeField;
  26. import com.vaadin.ui.InlineDateTimeField;
  27. /**
  28. * A converter that converts between <code>LocalDateTime</code> and
  29. * <code>Date</code>. This is used when a {@link DateTimeField} or
  30. * {@link InlineDateTimeField} is bound to a {@link Date} property.
  31. *
  32. * @author Vaadin Ltd
  33. * @since 8.0
  34. */
  35. public class LocalDateTimeToDateConverter
  36. implements Converter<LocalDateTime, Date> {
  37. private ZoneId zoneId;
  38. /**
  39. * Creates a new converter using the given time zone.
  40. *
  41. * @param zoneId
  42. * the time zone to use, not <code>null</code>
  43. */
  44. public LocalDateTimeToDateConverter(ZoneId zoneId) {
  45. this.zoneId = Objects.requireNonNull(zoneId,
  46. "Zone identifier cannot be null");
  47. }
  48. @Override
  49. public Result<Date> convertToModel(LocalDateTime localDate,
  50. ValueContext context) {
  51. if (localDate == null) {
  52. return Result.ok(null);
  53. }
  54. return Result.ok(Date.from(localDate.atZone(zoneId).toInstant()));
  55. }
  56. @Override
  57. public LocalDateTime convertToPresentation(Date date,
  58. ValueContext context) {
  59. if (date == null) {
  60. return null;
  61. }
  62. return Instant.ofEpochMilli(date.getTime()).atZone(zoneId)
  63. .toLocalDateTime();
  64. }
  65. }