myWallJSON
myWallJSON

Reputation: 9512

How to get compilation day from C++ defines?

So I play with arduino clock. Here is its wiki. It requires setup alike such:

clock.fillByYMD(2013,1,19);//Jan 19,2013
clock.fillByHMS(15,28,30);//15:28 30"
clock.fillDayOfWeek(SAT);//Saturday

So I tried parsing:

char compileTime[] = __TIME__;

So far I got:

  byte hour = getInt(compileTime, 0);
  byte minute = getInt(compileTime, 3);
  byte second = getInt(compileTime, 6);
  unsigned int hash =  hour * 60 * 60 + minute  * 60 + second; 
  clock.fillByHMS(hour, minute, second);
  clock.setTime();

where:

char getInt(const char* string, const int & startIndex) {
  return int(string[startIndex] - '0') * 10 + int(string[startIndex+1]) - '0';
}

I wonder how to set fillByYMD and fillDayOfWeek via compiler defines parsing?

Upvotes: 0

Views: 250

Answers (2)

Joachim Isaksson
Joachim Isaksson

Reputation: 180987

You'll have some conversion to do since the (numeric) month and weekday is not in the compile time data; this assumes a get4DigitInt and a slight change to getInt to allow for a space in the first position.

char compileDate[] = __DATE__;

int year = get4DigitInt(compileDate, 7);
int day = getInt(compileDate, 4);          // First character may be space
int month;
switch(compileDate[0]+compileDate[1]+compileDate[2]) {
    case 'J'+'a'+'n': month=1; break;
    case 'F'+'e'+'b': month=2; break;
    case 'M'+'a'+'r': month=3; break;
    case 'A'+'p'+'r': month=4; break;
    case 'M'+'a'+'y': month=5; break;
    case 'J'+'u'+'n': month=6; break;
    case 'J'+'u'+'l': month=7; break;
    case 'A'+'u'+'g': month=8; break;
    case 'S'+'e'+'p': month=9; break;
    case 'O'+'c'+'t': month=10; break;
    case 'N'+'o'+'v': month=11; break;
    case 'D'+'e'+'c': month=12; break;
}
std::tm time = { 0, 0, 0, day, month - 1, year - 1900 };
std::mktime(&time);
int day_of_week = time.tm_wday;   // 0=Sun, 1=Mon, ...

std::cout << "Time: " << hour << ":" << minute << ":" << second << std::endl;
std::cout << "Date: " << year << "-" << month << "-" << day << std::endl;
std::cout << "Day:  " << day_of_week << std::endl;

Upvotes: 2

LogicG8
LogicG8

Reputation: 1757

There is a standard predefined macro: __DATE__ It expands to a string constant containing the date the preprocessor was run. The string always contains 11 characters in this format "Jul 28 2013".

Code which determines the day of the week from the date can be found here.

Upvotes: 1

Related Questions