]> git.basschouten.com Git - openhab-addons.git/blob
a4f996c8dcdd91fb01839fd2782308728d0cf743
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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         return dt.toInstant().toEpochMilli() - now;
44     }
45
46     public static ZonedDateTime getCalendarForHour(int hour, ZoneId zone) {
47         return ZonedDateTime.now(zone).truncatedTo(ChronoUnit.DAYS).plus(hour, ChronoUnit.HOURS);
48     }
49
50     public static DateTimeType getDateTimeType(long time, TimeZoneProvider tz) {
51         return new DateTimeType(ZonedDateTime.ofInstant(Instant.ofEpochMilli(time), tz.getTimeZone()));
52     }
53
54     public static QuantityType<Time> getDuration(long millis) {
55         long minutes = millis / 60000;
56         return QuantityType.valueOf(minutes, Units.MINUTE);
57     }
58
59     public static String formatDate(long date, ZoneId zoneId) {
60         return ZonedDateTime.ofInstant(Instant.ofEpochMilli(date), zoneId).toString();
61     }
62
63     public static String getHourFrom(long timestamp, ZoneId zoneId) {
64         ZonedDateTime zdt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp), zoneId);
65         return String.format("%02d", zdt.getHour());
66     }
67 }