Arduino Playground is read-only starting December 31st, 2018. For more info please look at this Forum Post

Software Date Time library

This library has been superseded by a newer version that is available here

The DateTime library adds timekeeping capability to the Arduino without requiring external hardware. It allows a sketch to get the current second, minute, hour, day, month and year. It also provides time as a standard C time_t so elapsed times can be easily calculated and time values shared across different platforms.

The main advantages of software only clock is no hardware to buy or integrate, everything runs on the Arduino. The disadvantage is that time will be incorrect if the Arduino is reset.

The date and time needs to be set when the sketch starts, this can be through a synchronization message from on external time source such as a computer connected via the serial port. Once synchronized the Arduino crystal provides accuracy within a few seconds per day.

The download includes an example sketch and a readme.txt file to explain the basics of adding a library. It also includes an example Processing application showing how to synchronize time from an external computer.

Functional overview :

Properties of the DateTime library are:

 byte Hour;
 byte Minute;
 byte Second;
 byte Day;
 byte DayofWeek; // Sunday is day 0 
 byte Month;     // Jan is month 0
 byte Year;      // the Year minus 1900  

Methods:

void sync(time_t time);
a method to set the clock to an external time reference, this is usually done by receiving the time over the serial port but can also use other references such as WWV/DCF radio signals.

time_t now();
return the current time as seconds since midnight Jan 1 1970 (aka unix time)

boolean available();
refreshes the Date and Time properties. This returns true if the clock is synced, otherwise it returns false. This method should always be called just before using the time properties because the date and time properties are updated by this call.

Methods to convert to and from time components (hrs, secs, days, years etc) to time_t

void localTime(time_t *timep,byte *psec,byte *pmin,byte *phour,byte *pday,byte *pwday,byte *pmonth,byte *pyear);
extracts time components from time_t. Note that year here is the desired year minus 1900

time_t makeTime(byte sec, byte min, byte hour, byte day, byte month, int year );
returns time_t from time components, note that year here is full four digit year.

Companion Library for date strings

There is an optional companion library included in the download called DateTimeStrings that provides text strings for names of months and days of the week using program memory to conserve RAM space. The Library uses 310 bytes of flash if long strings are used and 240 bytes of flash for short strings. Both versions consume 10 bytes of RAM.

The methods of this class are:

char* monthStr(byte month);
Returns a string for the given month, January is month 0. The library can be compiled to produce either long (January) or short (Jan) versions of the months.

char* dayStr(byte day);
Returns a string for the given day of the week, Sunday is day 0. The library can be compiled to produce either long (Sunday) or short (Sun) versions of the days.

Memory usage:

The DateTime library uses 1470 bytes program flash, this can be reduced to just under 1000 bytes by commenting out the makeTime method.

DatetimeStrings uses 310 bytes program flash for long strings or 240 bytes program flash for short (3 character) strings. Both versions use 10 bytes of RAM.

Example sketch:

The test sketch included in the download demonstrates many of the capabilities of the library.

#include <DateTime.h>
#include <DateTimeStrings.h>

#define TIME_MSG_LEN  11   // time sync to PC is HEADER and unix time_t as ten ascii digits
#define TIME_HEADER  255   // Header tag for serial time sync message

void setup(){
  Serial.begin(19200);
}

void  loop(){  
  getPCtime();   // try to get time sync from pc        
  if(DateTime.available()) { // update clocks if time has been synced
    unsigned long prevtime = DateTime.now();
    while( prevtime == DateTime.now() )  // wait for the second to rollover
      ;
    DateTime.available(); //refresh the Date and time properties
    digitalClockDisplay( );   // update digital clock

    // send our time to an app listening on the serial port
    Serial.print( TIME_HEADER,BYTE); // this is the header for the current time
    Serial.println(DateTime.now());      
  }
}

void getPCtime() {
  // if time available from serial port, sync the DateTime library
  while(Serial.available() >=  TIME_MSG_LEN ){  // time message
    if( Serial.read() == TIME_HEADER ) {        
      time_t pctime = 0;
      for(int i=0; i < TIME_MSG_LEN -1; i++){  
        char c= Serial.read();          
        if( c >= '0' && c <= '9')  
          pctime = (10 * pctime) + (c - '0') ; // convert digits to a number            
      }  
      DateTime.sync(pctime);   // Sync DateTime clock to the time received on the serial port
    }  
  }
}

void digitalClockDisplay(){
  // digital clock display of current time
  Serial.print(DateTime.Hour,DEC);  
  printDigits(DateTime.Minute);  
  printDigits(DateTime.Second);
  Serial.print(" ");
  Serial.print(DateTimeStrings.dayStr(DateTime.DayofWeek));
  Serial.print(" ");  
  Serial.print(DateTimeStrings.monthStr(DateTime.Month));  
  Serial.print(" ");
  Serial.println(DateTime.Day, DEC);  
}

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

The downloaded files include a processing application that can be used with the example sketch to show how to synchronize time from an external computer. You may need to modify the processing application so it uses the serial port that your arduino is connected to.

On using and modifying libraries

Coming soon:

There is another companion library called DateTimeAlarms that allows multiple tasks to be scheduled and processed as if in parallel with the main sketch. Functions can be defined that will run at specific times or after a specified time period has elapsed. Alarms can be set to repeat at the same time each day, or to only trigger on the specified date and time. I will post the library when I can find time to finish the documentation.

Another library called RadioTime syncronises the DateTime library using DCF radio time signals. Alas, it also is awaiting time to do documentation before posting.

Questions, comments and suggestions on the library and documentation

Forum discussion
PM contact