]> git.basschouten.com Git - openhab-addons.git/blob
b1b09ed6ba82ab980dbf5a654268d7d0f940c1f1
[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.awattar.internal;
14
15 import java.time.Instant;
16 import java.time.ZoneId;
17 import java.time.ZonedDateTime;
18 import java.time.temporal.ChronoUnit;
19
20 import javax.measure.quantity.Time;
21
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.openhab.core.i18n.TimeZoneProvider;
24 import org.openhab.core.library.types.DateTimeType;
25 import org.openhab.core.library.types.QuantityType;
26 import org.openhab.core.library.unit.Units;
27
28 /**
29  * Some utility methods
30  *
31  * @author Wolfgang Klimt - initial contribution
32  */
33 @NonNullByDefault
34 public class AwattarUtil {
35
36     public static long getMillisToNextMinute(int mod, TimeZoneProvider timeZoneProvider) {
37         long now = Instant.now().toEpochMilli();
38         ZonedDateTime dt = ZonedDateTime.now(timeZoneProvider.getTimeZone()).truncatedTo(ChronoUnit.MINUTES);
39         int min = dt.getMinute();
40         int offset = min % mod;
41         offset = offset == 0 ? mod : offset;
42         dt = dt.plusMinutes(offset);
43         long result = dt.toInstant().toEpochMilli() - now;
44
45         return result;
46     }
47
48     public static ZonedDateTime getCalendarForHour(int hour, ZoneId zone) {
49         return ZonedDateTime.now(zone).truncatedTo(ChronoUnit.DAYS).plus(hour, ChronoUnit.HOURS);
50     }
51
52     public static DateTimeType getDateTimeType(long time, TimeZoneProvider tz) {
53         return new DateTimeType(ZonedDateTime.ofInstant(Instant.ofEpochMilli(time), tz.getTimeZone()));
54     }
55
56     public static QuantityType<Time> getDuration(long millis) {
57         long minutes = millis / 60000;
58         return QuantityType.valueOf(minutes, Units.MINUTE);
59     }
60
61     public static String formatDate(long date, ZoneId zoneId) {
62         return ZonedDateTime.ofInstant(Instant.ofEpochMilli(date), zoneId).toString();
63     }
64
65     public static String getHourFrom(long timestamp, ZoneId zoneId) {
66         ZonedDateTime zdt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp), zoneId);
67         return String.format("%02d", zdt.getHour());
68     }
69 }