]> git.basschouten.com Git - openhab-addons.git/blob
5d99e43ee2a6932cfba49c9f2a678e361fb05b0a
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.gardena.internal.util;
14
15 import java.text.ParseException;
16 import java.text.SimpleDateFormat;
17 import java.time.LocalDateTime;
18 import java.time.ZoneId;
19 import java.time.ZoneOffset;
20 import java.time.ZonedDateTime;
21 import java.util.Calendar;
22 import java.util.Date;
23
24 import org.apache.commons.lang.StringUtils;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 /**
29  * Utility class to convert a String to a date or calendar.
30  *
31  * @author Gerhard Riegler - Initial contribution
32  */
33 public class DateUtils {
34     private static final Logger LOGGER = LoggerFactory.getLogger(DateUtils.class);
35     private static final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd'T'HH:mm:ss'Z'",
36             "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "yyyy-MM-dd'T'HH:mm'Z'" };
37
38     /**
39      * Converts a string to a Date, trying different date formats used by Gardena.
40      */
41     public static Date parseToDate(String text) {
42         if (StringUtils.isNotBlank(text)) {
43             Date parsedDate = null;
44             for (String dateFormat : DATE_FORMATS) {
45                 try {
46                     parsedDate = new SimpleDateFormat(dateFormat).parse(text);
47                     ZonedDateTime gmt = ZonedDateTime.ofInstant(parsedDate.toInstant(), ZoneOffset.UTC);
48                     LocalDateTime here = gmt.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
49                     parsedDate = Date.from(here.toInstant(ZoneOffset.UTC));
50                     break;
51                 } catch (ParseException ex) {
52                 }
53             }
54             if (parsedDate == null) {
55                 LOGGER.error("Can't parse date {}", text);
56             }
57             return parsedDate;
58         } else {
59             return null;
60         }
61     }
62
63     /**
64      * Converts a string to a Calendar, trying different date formats used by Gardena.
65      */
66     public static Calendar parseToCalendar(String text) {
67         Date parsedDate = parseToDate(text);
68         if (parsedDate != null) {
69             Calendar cal = Calendar.getInstance();
70             cal.setTime(parsedDate);
71             return cal;
72         }
73         return null;
74     }
75 }