Reputation: 21
I am trying to calculate the time, in seconds, for a certain timestamp. How can I input a date and time into time_t so I can calculate the time from time(null)? (time(null) is 01/01/1970 if I understand it right)
Upvotes: 1
Views: 2004
Reputation: 3752
Adafruit's RTCLib has a unixtime function:
RTC_DS3231 _rtc; // or whichever chip you're using
_rtc.begin();
uint32_t unixtm = _rtc.now().unixtime();
Upvotes: 0
Reputation: 48083
Here is a simple example that computes the time more or less now, where I am:
#include <stdio.h>
#include <time.h>
int main()
{
time_t t;
struct tm tm;
/* fill in values for 2019-08-22 23:22:26 */
tm.tm_year = 2019 - 1900;
tm.tm_mon = 8 - 1;
tm.tm_mday = 22;
tm.tm_hour = 23;
tm.tm_min = 22;
tm.tm_sec = 26;
tm.tm_isdst = -1;
t = mktime(&tm);
printf("%ld\n", t);
}
As you can see, the values in some of the fields use mildly strange conventions: tm_mon
is 0-based, and tm_year
counts from 1900. Setting tm_isdst
to -1 means "I'm not sure if DST applied on August 22; you figure it out".
When I run it, this program prints 1566530546, which is indeed the number of seconds since midnight UTC on January 1, 1970. (If you run the program, though, you'll likely get a slightly different number, because it will work from 23:22:26 in your time zone.)
As the preceding paragraphs suggest, the mktime
function does take your time zone into account, as well as any necessary DST correction. If you want to do a similar conversion without these corrections, there's an analogous function called timegm
, although it's not Standard and not present on all systems.
The tm_wday
and tm_yday
(day of week and day of year) fields are ignored when you call mktime
, although they will have been filled in with their correct values when the function returns.
Upvotes: 3