but gets the same output.
My requirement is very simple . add or substract seconds / minutes / hour / date with a given date to obtain a new date & time
So if I add 1 to 2024-Feb-29 , it should return 2024-Mar-1 , instead this return 2024-Feb-30 which obviously is wrong. How can I get correct date ? or is it that Time.h or TimeLib.h is inefficient for this simple operation ? if so what is the solution ?
That does not use the Time library, instead it references the standard C library. The actual header file is time.h, not Time.h, and will produce an error when compiling on an operating system, such as linux, that has a case-sensitive file system. The confusion between Time.h and time.h on Windows is a primary reason the header file for the Time library was changed to TimeLib.h.
The year in the tmElements_t struct is stored as the number of years since 1970, not the actual calendar year. The time library has the macros CalendarYrToTm() and tmYearToCalendar() to convert between the two representations. You are getting the wrong output because setting tm.year to 2024 is overflowing the single byte used to store the year value.
Since time_t represents the date/time in seconds, there are pre-defined values in the Time library for adding/subtracting common time intervals, such as SECS_PER_DAY for the number of seconds in a day.
That did it. Thank you very much.
[ only thing is now I have to change a lot of code written for Time.h ]
Glad that it does work correctly. Thanks a lot every one.
I had use difftime() function to get difference between two times (Say 6:30 AM & 18:46 PM ) for computation. TimeLib.h doesn't seem to have that function. so How can I get this value from two tmElements_t ? thks
My approach is to convert the time and date to a unix timestamp, which is an unsigned long integer (the number of seconds since some epoch), and just subtract the earlier from the later.
In this example, I do the reverse, or add to get a later time/date:
//time_make_and_add
#include <TimeLib.h>
tmElements_t te; //Time elements structure
time_t unixTime; // a time stamp
void setup() {
Serial.begin(115200);
// 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() {}