Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Time.h and Unix timestamp #935

Closed
bill-orange opened this issue Dec 19, 2017 · 4 comments
Closed

Time.h and Unix timestamp #935

bill-orange opened this issue Dec 19, 2017 · 4 comments

Comments

@bill-orange
Copy link

Hardware:

Board: ESP32 TTGO Module
Core Installation/update date: unknown
IDE name: Arduino IDE
Flash Frequency: 80Mhz
Upload Speed: 115200

Description:

I notice that a few days ago time.h was added to the library. Good news. The example sketch works fine. I notice, however, that in the time.h structure there is tm_hour, tm_min, etc, but no unix time. Is there an easy way to get the unix timestamp with existing libraries?

@MarkusAD
Copy link
Contributor

Setup the same as example sketch then:

time_t now;

time(&now);
Serial.println(now);

@bill-orange
Copy link
Author

bill-orange commented Dec 20, 2017

Works like a charm. Thanks. I am still a bit confused by both your suggestion and the example sketch. I don't fully understand how time.h works which leaves me confused as to what portions of the code should go in setup(), be declared before setup() and a called within loop(). Right now I have everything pretty much in the function called by loop(), like the example, but it 'looks' wrong. Is this correct?

const char* ntpServer = "pool.ntp.org";

setup() {
configTime(0, 0, ntpServer)
};

unsigned long getTime() {
time_t now;
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
Serial.println("Failed to obtain time");
return(0);
}
time(&now);
return now;
}

@MarkusAD
Copy link
Contributor

getLocalTime() calls time() to fetch the unix timestamp and localtime_r() to convert that to local time, filling in the struct tm elements (tm_hour, tm_min, etc). It also has a timeout that waits for the time to be initialized, call it once in setup() to wait for the clock to be set. After that, if all you need is the unix timestamp you only need to call time().

@bill-orange
Copy link
Author

Got it! Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants