]> git.basschouten.com Git - openhab-addons.git/blob
b60061dbd8e2794e40e9b2d105ac88d170f1453f
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.plugwiseha.internal.api.model.converter;
14
15 import java.time.ZonedDateTime;
16 import java.time.format.DateTimeFormatter;
17 import java.time.format.DateTimeParseException;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
25
26 /**
27  * The {@link DateTimeConverter} provides a SingleValueConverter for use by XStream when converting
28  * XML documents with a zoned date/time field.
29  * 
30  * @author B. van Wetten - Initial contribution
31  */
32
33 @NonNullByDefault
34 public class DateTimeConverter extends AbstractSingleValueConverter {
35
36     private final Logger logger = LoggerFactory.getLogger(DateTimeConverter.class);
37     private static final DateTimeFormatter FORMAT = DateTimeFormatter.ISO_OFFSET_DATE_TIME; // default Date format that
38
39     @Override
40     public boolean canConvert(@Nullable @SuppressWarnings("rawtypes") Class type) {
41         if (type == null) {
42             return false;
43         }
44         return ZonedDateTime.class.isAssignableFrom(type);
45     }
46
47     @Override
48     public @Nullable ZonedDateTime fromString(@Nullable String str) {
49         if (str == null || str.isBlank()) {
50             return null;
51         }
52
53         try {
54             return ZonedDateTime.parse(str, DateTimeConverter.FORMAT);
55         } catch (DateTimeParseException e) {
56             logger.debug("Invalid datetime format in {}", str);
57             return null;
58         }
59     }
60
61     public String toString(ZonedDateTime dateTime) {
62         return dateTime.format(DateTimeConverter.FORMAT);
63     }
64 }