]> git.basschouten.com Git - openhab-addons.git/blob
0e4ef1314854b7c4e7f356d60a0f87132760d29c
[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.ihc.internal.converters;
14
15 import java.time.ZonedDateTime;
16 import java.util.Calendar;
17 import java.util.GregorianCalendar;
18 import java.util.TimeZone;
19
20 import org.eclipse.jdt.annotation.NonNull;
21 import org.openhab.binding.ihc.internal.ws.exeptions.ConversionException;
22 import org.openhab.binding.ihc.internal.ws.resourcevalues.WSDateValue;
23 import org.openhab.binding.ihc.internal.ws.resourcevalues.WSTimeValue;
24 import org.openhab.core.library.types.DateTimeType;
25
26 /**
27  * DateTimeType {@literal <->} WSDateValue converter.
28  *
29  * @author Pauli Anttila - Initial contribution
30  */
31 public class DateTimeTypeWSDateValueConverter implements Converter<WSDateValue, DateTimeType> {
32
33     @Override
34     public DateTimeType convertFromResourceValue(@NonNull WSDateValue from,
35             @NonNull ConverterAdditionalInfo convertData) throws ConversionException {
36         Calendar cal = dateTimeToCalendar(from, null);
37         return new DateTimeType(ZonedDateTime.ofInstant(cal.toInstant(), TimeZone.getDefault().toZoneId()));
38     }
39
40     @Override
41     public WSDateValue convertFromOHType(@NonNull DateTimeType from, @NonNull WSDateValue value,
42             @NonNull ConverterAdditionalInfo convertData) throws ConversionException {
43         Calendar cal = GregorianCalendar.from(from.getZonedDateTime());
44         short year = (short) cal.get(Calendar.YEAR);
45         byte month = (byte) (cal.get(Calendar.MONTH) + 1);
46         byte day = (byte) cal.get(Calendar.DAY_OF_MONTH);
47         return new WSDateValue(value.resourceID, year, month, day);
48     }
49
50     private Calendar dateTimeToCalendar(WSDateValue date, WSTimeValue time) {
51         Calendar cal = new GregorianCalendar(2000, 01, 01);
52         if (date != null) {
53             short year = date.year;
54             short month = date.month;
55             short day = date.day;
56             cal.set(year, month - 1, day, 0, 0, 0);
57         }
58         if (time != null) {
59             int hour = time.hours;
60             int minute = time.minutes;
61             int second = time.seconds;
62             cal.set(2000, 0, 1, hour, minute, second);
63         }
64         return cal;
65     }
66 }