AceTime  3.0.0
Date and time classes for Arduino that support timezones from the TZ Database.
TimeOffset.cpp
1 /*
2  * MIT License
3  * Copyright (c) 2018 Brian T. Park
4  */
5 
6 #include <string.h> // strlen()
7 #include <AceCommon.h>
8 #include "common/DateStrings.h"
9 #include "TimeOffset.h"
10 
11 using ace_common::printPad2To;
12 
13 namespace ace_time {
14 
15 void TimeOffset::printTo(Print& printer) const {
16  int8_t hour;
17  int8_t minute;
18  int8_t second;
19  toHourMinuteSecond(hour, minute, second);
20 
21  if (mSeconds < 0) {
22  printer.print('-');
23  hour = -hour;
24  minute = -minute;
25  second = -second;
26  } else {
27  printer.print('+');
28  }
29  printPad2To(printer, hour, '0');
30  printer.print(':');
31  printPad2To(printer, minute, '0');
32  if (second != 0) {
33  printer.print(':');
34  printPad2To(printer, second, '0');
35  }
36 }
37 
38 TimeOffset TimeOffset::forOffsetString(const char* offsetString) {
39  // Verify length of ISO 8601 string, either 6 ("-hh:mm") or 9 ("-hh:mm:ss").
40  uint8_t len = strlen(offsetString);
41  if (len != 6 && len != 9) {
42  return forError();
43  }
44 
45  return forOffsetStringChainable(offsetString);
46 }
47 
49  const char* s = offsetString;
50 
51  // '+' or '-'
52  char sign = *s++;
53  if (sign != '-' && sign != '+') {
54  return forError();
55  }
56 
57  // hour
58  int8_t hour = (*s++ - '0');
59  hour = 10 * hour + (*s++ - '0');
60  s++; // skip ':'
61 
62  // minute
63  int8_t minute = (*s++ - '0');
64  minute = 10 * minute + (*s++ - '0');
65 
66  // second if necessary
67  int8_t second = 0;
68  if (*s) {
69  s++; // skip ':'
70  second = (*s++ - '0');
71  second = 10 * second + (*s++ - '0');
72  s++;
73  }
74 
75  offsetString = s;
76  if (sign == '+') {
77  return forHourMinuteSecond(hour, minute, second);
78  } else {
79  return forHourMinuteSecond(-hour, -minute, -second);
80  }
81 }
82 
83 }
A thin wrapper that represents a time offset from a reference point, usually 00:00 at UTC,...
Definition: TimeOffset.h:56
void toHourMinuteSecond(int8_t &hour, int8_t &minute, int8_t &second) const
Extract hour, minute, second from the offset.
Definition: TimeOffset.h:149
static TimeOffset forOffsetString(const char *offsetString)
Create from an offset string (e.g.
Definition: TimeOffset.cpp:38
static TimeOffset forError()
Return an error indicator.
Definition: TimeOffset.h:122
static TimeOffset forHourMinuteSecond(int8_t hour, int8_t minute, int8_t second)
Create a TimeOffset fro (hour, minute, second) offset.
Definition: TimeOffset.h:84
void printTo(Print &printer) const
Print the human readable string, including a "-" or "+" prefix, in the form of "+/-hh:mm" or "+/-hh:m...
Definition: TimeOffset.cpp:15
static TimeOffset forOffsetStringChainable(const char *&offsetString)
Variant of forOffsetString() that updates the string pointer to the next unprocessed character.
Definition: TimeOffset.cpp:48