(deleted)
Timelib.h is not out of date.
//time_make_and_add
#include "TimeLib.h"
tmElements_t te; //Time elements structure
time_t unixTime; // a time stamp
void setup() {
Serial.begin(9600);
// new internal clock setting.
// convert a date and time into unix time, offset 1970
te.Second = 0;
te.Hour = 23; //11 pm
te.Minute = 0;
te.Day = 1;
te.Month = 1;
te.Year = 2017 - 1970; //Y2K, in seconds = 946684800UL
unixTime = makeTime(te);
Serial.print("Example 1/1/2017 23:00 unixTime = ");
Serial.println(unixTime);
setTime(unixTime); //set the current time to the above entered
Serial.print("now() = ");
Serial.println(now());
// print as date_time
print_date_time();
// add
unixTime += 7200UL; //add 2 hours
setTime(unixTime);
Serial.println("After adding 2 hours");
Serial.print("now() = ");
Serial.println(now());
print_date_time();
}
void print_date_time() { //easy way to print date and time
char buf[40];
sprintf(buf, "%02d/%02d/%4d %02d:%02d:%02d", day(), month(), year(), hour(), minute(), second());
Serial.println(buf);
}
void loop() {}
(deleted)
The code I posted works correctly. Your correction doesn't make sense, because it is not clear what "format" you are referring to. In Arduino TimeLib.h, days of month, days of week and months are counted starting from 1.
From the library docs:
The functions available in the library include
hour(); // the hour now (0-23)
minute(); // the minute now (0-59)
second(); // the second now (0-59)
day(); // the day now (1-31)
weekday(); // day of the week (1-7), Sunday is day 1
month(); // the month now (1-12)
year(); // the full four digit year: (2009, 2010 etc)
This code does what you asked:
#include <TimeLib.h>
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
time_t t = 1572214235; //unix timestamp
setTime(t);
Serial.print("Date: ");
Serial.print(day());
Serial.print("/");
Serial.print(month());
Serial.print("/");
Serial.print(year());
Serial.print(" ");
Serial.print(hour());
Serial.print(":");
Serial.print(minute());
Serial.print(":");
Serial.println(second()); //prints Date: 27/10/2019 22:10:35
}
void loop() {
// put your main code here, to run repeatedly:
}
the problem with your code @jremington is, that it sets the system's time, which is not desired
the snippets on Stack Exchange in the 7 answers of which two are my, show different options and variations how to convert time from string
adrianTNT uses the C time structure and functions and there the month is count from 0
the problem with your code @jremington is, that it sets the system's time, which is not desired
It does exactly what the OP asked, and the OP stated no such preference regarding the system time.
I desired to use TimeLib.h, where the months start with 1, and to set the system time. So, there is no problem with the posted code.