]> git.basschouten.com Git - openhab-addons.git/blob
c39fe56238464b3814646f258b1cd060797c7055
[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.mqtt.generic.values;
14
15 import java.time.format.DateTimeFormatter;
16 import java.util.List;
17
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.openhab.core.library.CoreItemFactory;
21 import org.openhab.core.library.types.DateTimeType;
22 import org.openhab.core.library.types.StringType;
23 import org.openhab.core.types.Command;
24 import org.openhab.core.types.UnDefType;
25
26 /**
27  * Implements a datetime value.
28  *
29  * @author David Graeff - Initial contribution
30  */
31 @NonNullByDefault
32 public class DateTimeValue extends Value {
33     public DateTimeValue() {
34         super(CoreItemFactory.DATETIME, List.of(DateTimeType.class, StringType.class));
35     }
36
37     @Override
38     public void update(Command command) throws IllegalArgumentException {
39         if (command instanceof DateTimeType) {
40             state = ((DateTimeType) command);
41         } else {
42             state = DateTimeType.valueOf(command.toString());
43         }
44     }
45
46     @Override
47     public String getMQTTpublishValue(@Nullable String pattern) {
48         if (state == UnDefType.UNDEF) {
49             return "";
50         }
51         String formatPattern = pattern;
52         if (formatPattern == null || "%s".contentEquals(formatPattern)) {
53             return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(((DateTimeType) state).getZonedDateTime());
54         }
55         return String.format(formatPattern, ((DateTimeType) state).getZonedDateTime());
56     }
57 }