2 * Copyright (c) 2010-2020 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.gardena.internal.util;
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;
24 import org.apache.commons.lang.StringUtils;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
29 * Utility class to convert a String to a date or calendar.
31 * @author Gerhard Riegler - Initial contribution
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'" };
39 * Converts a string to a Date, trying different date formats used by Gardena.
41 public static Date parseToDate(String text) {
42 if (StringUtils.isNotBlank(text)) {
43 Date parsedDate = null;
44 for (String dateFormat : DATE_FORMATS) {
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));
51 } catch (ParseException ex) {
54 if (parsedDate == null) {
55 LOGGER.error("Can't parse date {}", text);
64 * Converts a string to a Calendar, trying different date formats used by Gardena.
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);