Different ways to set the time on the DS1307 RTC

Hi everyone, I have a DS1307 real time clock and I’m trying to figure how to set the time using time expressed as seconds. I’m using the RTClib library.

I know that I can set the time using this:

rtc.adjust(DateTime(2022, 08, 08, 12, 34, 56)); //set date-time manualy:yr,mo,dy,hr,mn,sec

but how can I set the time if the time I have is in seconds?

Time: 12:34:56 which equates to: 45296 (seconds)

Doing rtc.adjust(DateTime(45296)); doesn’t give the correct time.

Reverse the calculation so you get hours, minutes and seconds from the seconds value that you have. Next use rtc.adjust(DateTime(2022, 08, 08, hours, minutes, seconds)).

Hi,
try this code:

// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include "RTClib.h"

RTC_DS1307 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {
  Serial.begin(57600);

#ifndef ESP8266
  while (!Serial); // wait for serial port to connect. Needed for native USB
#endif

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    Serial.flush();
    abort();
  }
   unsigned long myUnixTime = 1659916800;  //Time in seconds from 1/1/1970 to today 0 h
   unsigned long mytimeSeg = (1234); //(time from 0 h to now in seg )
  //rtc.adjust(DateTime(2022, 8, 8, 0, 0, 0));
   myUnixTime = myUnixTime +   (mytimeSeg);  //(time from 0 h to now in seg )
   rtc.adjust(myUnixTime);
}

void loop () {
    DateTime now = rtc.now();
   
    Serial.print(" since midnight 1/1/1970 = ");
    Serial.print(now.unixtime());
    Serial.print("s = ");
    Serial.print(now.unixtime() / 86400L);
    Serial.println("d");

    Serial.println();
    delay(3000);
}
1 Like

Take a look at Unix time, it may have what you want.

1 Like

Thank you everyone. It looks like Unix time might be the way to go and I'm looking more into it now.

1 Like

Can you mark it solved. Thanks

Ola,
se seu problema foi resolvido, faça uma gentileza a todos do fórum, principalmente a quem te ajudou.
Escreva [Resolvido] antes do título do seu tópico, assim se alguém pesquisar e encontrar seu tópico saberá como é a solução.

E, se foi resolvido por alguma ajuda, marque a que melhor descreve sua solução.

Hi,
if your problem was solved, do a kindness to everyone on the forum, especially to those who helped you.
Write [Solved] before your topic title, so if someone searches and finds your topic, they'll know what the solution looks like.
And if it was solved by some help, please tick the one that best describes your solution.

@ruilviana, English please, google translate is working overtime :smiley:

Sorry;

thanks for the alert.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.