arduino-libraries / RTCZero

RTC Library for SAMD21 based boards
http://arduino.cc/en/Reference/RTC
GNU Lesser General Public License v2.1
77 stars 78 forks source link

Add function(s) to return ISO8601 time strings #35

Open tigoe opened 6 years ago

tigoe commented 6 years ago

It's really common to need to send a UTC time string to a server, or log it in a data logger. Here's a version I've been writing with some frequency that might be a good addition to the API, once this function is optimized.

String getUTC() {
  //2015-03-25T12:00:00Z
  String result = "20";

  if (rtc.getYear() < 9) {
    result += "0";
  }
  result += String(rtc.getYear());
  result += "-";
  if (rtc.getMonth() < 9) {
    result += "0";
  }
  result += String(rtc.getMonth());
  result += "-";
  if (rtc.getDay() < 9) {
    result += "0";
  }
  result += String(rtc.getDay());
  result += "T";
  if (rtc.getHours() < 9) {
    result += "0";
  }
  result += String(rtc.getHours());
  result += ":";
  if (rtc.getMinutes() < 9) {
    result += "0";
  }
  result += String(rtc.getMinutes());
  result += ":";
  if (rtc.getSeconds() < 9) {
    result += "0";
  }
  result += String(rtc.getSeconds());
  result += "-5";
  return result;
}