0

I am working on this Arduino test application as a part of a bigger project. I have connected my Arduino to a Grove RTC (Realtime clock DS1307) module which is now spitting out date and time in my serial monitor. However the year is wrong. As seen on the below picture it is showing the value 46 in the Year field.

Serial monitor

Below is the two methods i am using to get date and time and then print it out. I get the year value from the Year field of the tmElements struct. The tmElements type is residing in the Time library.

// Gets date and time and prints out in "DD/MM/YYYY - HH:MM:SS" format.
void getTime(){
  tmElements_t tm;
  if (RTC.read(tm)){
    getFormattedValue(tm.Day);
    Serial.print("/");
    getFormattedValue(tm.Month);
    Serial.print("/");
    Serial.print(tm.Year);
    Serial.print(" - ");
    getFormattedValue(tm.Hour);
    Serial.print(":");
    getFormattedValue(tm.Minute);
    Serial.print(":");
    getFormattedValue(tm.Second);
    Serial.println();
  }
}

// Formats the time value to two digits. Example: if hour is 7 it will be formatted as 07.
void getFormattedValue(int number) {
  if (number >= 0 && number < 10) {
    Serial.write('0');
  }
  Serial.print(number);
}

How come I am getting this wrong value? Can somebody please guide me in the right direction?

RonRonDK
  • 425
  • 6
  • 22

1 Answers1

1

Ahh.. Already found the problem myself. The problem was that I didn't use the tmYearToCalendar() method.

So instead of:

Serial.print(tm.Year);

It had to be:

Serial.print(tmYearToCalendar(tm.Year));

Works like a charm now. Just thought I would share it with you all.

RonRonDK
  • 425
  • 6
  • 22
  • 1
    Just to elaborate, the tmYearToCalendar() method just adds 1970 to the value of tm.Year. That is because tm.Year is the number of years since 1970. – RonRonDK Mar 18 '16 at 08:13
  • so seeing you are pretty nifty with the coding :D and using DS1307, I have a question, I'm using the RTC library , rtc_set_date method to be exact , and I can set and get the month and date alright , but when it comes to year , when I set it to 2002 , it some how gets set to 132 for some reason because when I try to get it , it prints 132, do you have any idea why? I tried passing integer and passing a char variable both containing the value 2002 , and the result was the same – Hitman2847 Jun 02 '21 at 08:32