Time: unix to ISO8601 (yyyy-mm-dd(time))

I am attempting to go from unix to ISO8601 for a webserver (m2x). Using NTP to get the time, and RTClib.h or Time.h libraries, what would be the best way to get into the time format the website requires? the full ISOcode has to look like this: yyyy-mm-dd T hh:mm:ss.123 (without spaces). I then somehow need to get this into an array that is outlined in the header.

Im using an UNO r3 (but if it makes any difference i'll have to use a mega by the time im done...)

I am going to use adafruit's NTP example as a starting point:

/***************************************************
  This is an example for the Adafruit CC3000 Wifi Breakout & Shield

  Designed specifically to work with the Adafruit WiFi products:
  ----> https://www.adafruit.com/products/1469

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried, Kevin Townsend and Phil Burgess for
  Adafruit Industries.  BSD license, all text above must be included
  in any redistribution
 ****************************************************/

/*
This example queries an NTP time server to get the current "UNIX time"
(seconds since 1/1/1970, UTC (GMT)), then uses the Arduino's internal
timer to keep relative time.  The clock is re-synchronized roughly
once per day.  This minimizes NTP server misuse/abuse.

The RTClib library (a separate download, and not used here) contains
functions to convert UNIX time to other formats if needed.
*/

#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <RTClib.h>

// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!
// These can be any two pins
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10
// Use hardware SPI for the remaining pins
// On an UNO, SCK = 13, MISO = 12, and MOSI = 11
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
                                         SPI_CLOCK_DIVIDER); // you can change this clock speed but DI
unixtime 
#define WLAN_SSID       "HOME-61B2"        // cannot be longer than 32 characters!
#define WLAN_PASS       "0C6B7DEB3241400F"
#define WLAN_SECURITY   WLAN_SEC_WPA2

Adafruit_CC3000_Client client;

const unsigned long
  connectTimeout  = 15L * 1000L, // Max time to wait for server connection
  responseTimeout = 15L * 1000L; // Max time to wait for data from server
int
  countdown       = 0;  // loop() iterations until next time server query
unsigned long
  lastPolledTime  = 0L, // Last value retrieved from time server
  sketchTime      = 0L; // CPU milliseconds since last server query


void setup(void)
{
  Serial.begin(115200);
  Serial.println(F("Hello, CC3000!\n")); 

  displayDriverMode();
  
  Serial.println(F("\nInitialising the CC3000 ..."));
  if (!cc3000.begin()) {
    Serial.println(F("Unable to initialise the CC3000! Check your wiring?"));
    for(;;);
  }

  uint16_t firmware = checkFirmwareVersion();
  if (firmware < 0x113) {
    Serial.println(F("Wrong firmware version!"));
    for(;;);
  } 
  
  displayMACAddress();
  
  Serial.println(F("\nDeleting old connection profiles"));
  if (!cc3000.deleteProfiles()) {
    Serial.println(F("Failed!"));
    while(1);
  }

  /* Attempt to connect to an access point */
  char *ssid = WLAN_SSID;             /* Max 32 chars */
  Serial.print(F("\nAttempting to connect to ")); Serial.println(ssid);
  
  /* NOTE: Secure connections are not available in 'Tiny' mode! */
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }
   
  Serial.println(F("Connected!"));
  
  /* Wait for DHCP to complete */
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP()) {
    delay(100); // ToDo: Insert a DHCP timeout!
  }

  /* Display the IP address DNS, Gateway, etc. */  
  while (!displayConnectionDetails()) {
    delay(1000);
  }
}


// To reduce load on NTP servers, time is polled once per roughly 24 hour period.
// Otherwise use millis() to estimate time since last query.  Plenty accurate.
void loop(void) {

  if(countdown == 0) {            // Time's up?
    unsigned long t  = getTime(); // Query time server
    if(t) {                       // Success?
      lastPolledTime = t;         // Save time
      sketchTime     = millis();  // Save sketch time of last valid time query
      countdown      = 24*60*4-1; // Reset counter: 24 hours * 15-second intervals
    }
  } else {
    countdown--;                  // Don't poll; use math to figure current time
  }

  unsigned long currentTime = lastPolledTime + (millis() - sketchTime) / 1000;

  Serial.print(F("Current UNIX time: "));
  Serial.print(currentTime);
  Serial.println(F(" (seconds since 1/1/1970 UTC)"));

  delay(15000L); // Pause 15 seconds
}

then attempt to integrate the RTClb.h or Time.h libraries. i can post examples those libraries if needed.

thanks

EDIT: alternatively, instead of using ntp.gov, is there one that will send me the data in the form i need off the bat (that the arduino can then use millis() to keep accurate?)

The Time library has functions which giver you hours, minutes, seconds, day, months, and years all of which take a time_t variable

I didnt realize that calling up any of the functions would do the conversion. So that was the first fundamental problem... the second is trying to figure how to start/set the time in the first place. I was thinking along the following lines, but i only get "0" for a result, a compile error (depending on how i try to set the variables.). Once i have this working, i should be able to start integrading it with my internet time sketch.

#include <Time.h>
#include <Wire.h>
int Year;
int t;
void setup() {

Serial.begin(115200);
t=1418354574 ;
setTime (time_t=t);
Serial.println (Year);

}

void loop() {}

thanks!

Edit:

ignore that snippet of code, even though it doesnt work i think the following was a better idea... wrong anyway, but a better idea...

#include <Time.h>
#include <Wire.h>
int Year;
int t=1418354574 ;
void setup() {

Serial.begin(115200);
time_t (t);
Serial.println (Year);

}

void loop() {}

EDIT 2
better idea yet... but still failing. Now it gives me 1970 as the year, which i suppose is a step in the right direction when it was giving me 0 before.

#include <Time.h>
#include <Wire.h>
#include <SoftwareSerial.h>
int t=1418354574 ; //time in UNIX when i started this sketch
void setup() {

Serial.begin(115200);
time_t t = now();

Serial.print (year(t));
}

void loop() {}

Here is a sketch which sets the internal system time to a Unix Time Stamp.

#include <Time.h> 
uint32_t unixTimeStamp = 1418354574;

uint32_t syncProvider()
{
  return unixTimeStamp;
}

void setup() 
{
  Serial.begin(9600);
  setSyncProvider(syncProvider);//sets internal clock
  if(timeStatus() != timeSet) 
    Serial.println("Unable to sync with the unixTimeStamp");
  else
    Serial.println("unixTimeStamp has set the system time");   
}

void loop() 
{
  timeDateDisplay();  
  delay(1000);
}

void timeDateDisplay(void)
{

  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(' ');
  Serial.print(month());
  Serial.print("/");
  Serial.print(day());
  Serial.print("/");
  Serial.print(year()); 
  Serial.println(); 
  Serial.print("Unix Time ");
  Serial.println(now());
  Serial.println();
}

void printDigits(int digits)
{
  // utility function for digital clock display: prints preceding colon and leading 0
  Serial.print(':');
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

This NTP clock is right off the Time.h library examples, I added LCD display.

#include <Wire.h>
#include <SPI.h>         
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <Time.h>
#include <Timezone.h>
#include <LiquidCrystal_I2C.h>

#define DEBUG_ON

#ifdef DEBUG_ON
#define DEBUG_PRINT(x)   Serial.print(x)
#define DEBUG_PRINTLN(x) Serial.println(x)
#define SERIAL_START(x)  Serial.begin(x)
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTLN(x)
#define SERIAL_START(x)
#endif
//
LiquidCrystal_I2C lcd(0x27, 16, 2);
uint8_t clock[8] = {0x0,0xe,0x15,0x17,0x11,0xe,0x0}; // fetching time indicator
//
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
unsigned int localPort = 8888;      // local port to listen for UDP packets
IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov NTP server
// IPAddress timeServer(132, 163, 4, 102); // time-b.timefreq.bldrdoc.gov NTP server
// IPAddress timeServer(132, 163, 4, 103); // time-c.timefreq.bldrdoc.gov NTP server
const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets 
const char *dayOfWeek[] = {"Null","Sunday ","Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "};
// 
EthernetUDP Udp; // A UDP instance to let us send and receive packets over UDP
TimeChangeRule usEDT = {"EDT", Second, Sun, Mar, 2, -240};  //Eastern Daylight Time = UTC - 4 hours
TimeChangeRule usEST = {"EST", First, Sun, Nov, 2, -300};   //Eastern Standard Time = UTC - 5 hours
Timezone usET(usEDT, usEST);
TimeChangeRule *tcr;
boolean justStarted = true;
//
void setup() 
{
  Serial.begin(9600);
  //
  DEBUG_PRINTLN(F("configuring ethernet"));
  if (Ethernet.begin(mac) == 0) // start Ethernet and UDP
  {
    DEBUG_PRINTLN(F("Failed to configure Ethernet using DHCP")); 
    while(true){
    }
  }
  //
  Udp.begin(localPort);
  //
  lcd.init();
  lcd.clear();
  lcd.backlight();
  lcd.createChar(0, clock);
  lcd.print("Hello, World!");
  delay(3000);
}
//
void loop()
{
  updateLCD();
  getNTPtime();
}
//
void updateLCD()
{
  
  static int lastSecond; 
  time_t rightNow = now();
  if (second(rightNow) != lastSecond)
  {
    lcd.setCursor(0,0);
    lcd.print(F("Time:"));
    DEBUG_PRINT(F("Time:"));
    lcd.print(hourFormat12(rightNow) < 10 ? F(" ") : F(""));
    DEBUG_PRINT(hourFormat12(rightNow) < 10 ? F(" ") : F(""));
    lcd.print(hourFormat12(rightNow));
    DEBUG_PRINT(hourFormat12(rightNow));
    lcd.print(minute(rightNow) < 10 ? F(":0") : F(":"));
    DEBUG_PRINT(minute(rightNow) < 10 ? F(":0") : F(":"));
    lcd.print(minute(rightNow));
    DEBUG_PRINT(minute(rightNow));
    lcd.print(second(rightNow) < 10 ? F(":0") : F(":"));
    DEBUG_PRINT(second(rightNow) < 10 ? F(":0") : F(":"));
    lcd.print(second(rightNow));
    DEBUG_PRINT(second(rightNow));
    lcd.print(isAM() ? "am" : "pm");
    DEBUG_PRINT(isAM() ? " am " : " pm ");
    lcd.setCursor(0,1);
    lcd.print(dayOfWeek[weekday(rightNow)]);
    DEBUG_PRINTLN(dayOfWeek[weekday(rightNow)]);
    lcd.print(F("      "));
    lcd.setCursor(11,1);
    lcd.print(month(rightNow) < 10 ? F(" ") : F(""));
    lcd.print(month(rightNow));
    lcd.print(day(rightNow) < 10 ? F("/0") : F("/"));
    lcd.print(day(rightNow));
  }
  lastSecond = second(rightNow);
}
//
unsigned long sendNTPpacket(IPAddress& address) // Send an NTP request to the time server at the given address 
{
  memset(packetBuffer, 0, NTP_PACKET_SIZE); 
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;            // Stratum, or type of clock
  packetBuffer[2] = 6;            // Polling Interval
  packetBuffer[3] = 0xEC;         // Peer Clock Precision
  packetBuffer[12]  = 49; 
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;		   
  Udp.beginPacket(address, 123); //NTP requests are to port 123
  Udp.write(packetBuffer,NTP_PACKET_SIZE);
  Udp.endPacket(); 
}
//
void receiveTime(unsigned long newTime)
{
  DEBUG_PRINT(F("Time value received: "));
  int lastSecond = second();
  int lastMinute = minute();
  int lastHour = hour();
  setTime(newTime);
  if ((second() != lastSecond) || (minute() != lastMinute) || (hour() != lastHour))
  {
    DEBUG_PRINTLN(F("Clock updated...."));
    DEBUG_PRINT(F("Sensor's time currently set to:"));
    DEBUG_PRINT(hourFormat12() < 10? F(" 0") : F(" "));
    DEBUG_PRINT(hourFormat12());
    DEBUG_PRINT(minute() < 10? F(":0") : F(":"));
    DEBUG_PRINT(minute());
    DEBUG_PRINTLN(isAM()? F("am") : F("pm"));
    DEBUG_PRINT(month());
    DEBUG_PRINT(F("/"));
    DEBUG_PRINT(day());
    DEBUG_PRINT(F("/"));
    DEBUG_PRINTLN(year());
    DEBUG_PRINTLN(dayOfWeek[weekday()]);
  }
  lcd.setCursor(15,0);
  lcd.print(F(" "));
}
//
void getNTPtime()
{
  static unsigned long lastUpdateTime;
  const unsigned long interval = 60000UL;
  if ((millis() - lastUpdateTime >= interval))
  {
    lcd.setCursor(15,0);
    lcd.write(0);
    sendNTPpacket(timeServer); // send an NTP packet to a time server
    delay(1000);  
    if (Udp.parsePacket()) 
    {  
      Udp.read(packetBuffer,NTP_PACKET_SIZE);  // read the packet into the buffer
      unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
      unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);  
      unsigned long secsSince1900 = highWord << 16 | lowWord;  
      DEBUG_PRINT(F("Seconds since Jan 1 1900 = "));
      DEBUG_PRINTLN(secsSince1900);               
      Serial.print(F("Unix time = "));
      time_t utcEpoch = secsSince1900 - 2208988800UL;//seventyYears = 2208988800UL
      DEBUG_PRINTLN(utcEpoch);                               
      receiveTime(usET.toLocal(utcEpoch, &tcr) + 2);  //about 2 seconds to call for time
    }
    lastUpdateTime += interval;
  }
}

you may have to adjust the LCD library to get it to compile, I use this library.

int t=1418354574 ;

A size 194 foot in a size 12 shoe, huh. To quote Foghorn Leghorn, "Pay attention, boy!".