2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.ihc.internal.converters;
15 import java.time.ZonedDateTime;
16 import java.util.Calendar;
17 import java.util.GregorianCalendar;
18 import java.util.TimeZone;
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;
27 * DateTimeType <-> WSDateValue converter.
29 * @author Pauli Anttila - Initial contribution
31 public class DateTimeTypeWSDateValueConverter implements Converter<WSDateValue, DateTimeType> {
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()));
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);
50 private Calendar dateTimeToCalendar(WSDateValue date, WSTimeValue time) {
51 Calendar cal = new GregorianCalendar(2000, 01, 01);
53 short year = date.year;
54 short month = date.month;
56 cal.set(year, month - 1, day, 0, 0, 0);
59 int hour = time.hours;
60 int minute = time.minutes;
61 int second = time.seconds;
62 cal.set(2000, 0, 1, hour, minute, second);