3
#include <ESP8266WiFi.h>
#include <time.h>
const char* ssid = "";
const char* password = "";
int timezone = 3;
int dst = 0;
void setup() {
 Serial.begin(115200);
 Serial.setDebugOutput(true);
 WiFi.mode(WIFI_STA);
 WiFi.begin(ssid, password);
 Serial.println("\nConnecting to WiFi");
 while (WiFi.status() != WL_CONNECTED) {
 Serial.print(".");
 delay(1000);
 }
 configTime(timezone * 3600, dst * 0, "pool.ntp.org", "time.nist.gov");
 Serial.println("\nWaiting for time");
 while (!time(nullptr)) {
 Serial.print(".");
 delay(1000);
 }
 Serial.println("");
}
void loop() {
 time_t now = time(nullptr);
 Serial.println(ctime(&now));
 delay(1000);
}

This is my code, but it shows the time like this: Sun Jul 23 15:21:12 2017. But what I want it to do is to only show the current hour, not everything. Is it possible to do that?

dda
1,5951 gold badge12 silver badges17 bronze badges
asked Jul 23, 2017 at 12:22
5
  • 2
    Use gmtime() or localtime() instead of ctime(). Print the hour field tm_hour in the struct tm. Commented Jul 23, 2017 at 13:06
  • Welcome to the site. Next time for aligning code, select code and press ctrl+k Commented Jul 23, 2017 at 13:20
  • @MikaelPatel I am a beginner at this, could you please give me an example of how it should look like? Commented Jul 23, 2017 at 13:30
  • @MikaelPatel Okay i tried this Serial.println(gmtime(tm_hour)); but i get an error "'tm_hour' was not declared in this scope" Commented Jul 23, 2017 at 15:13
  • Here is an example of gmtime() and the struct tm; cplusplus.com/reference/ctime/gmtime Commented Jul 23, 2017 at 16:23

1 Answer 1

3

The easiest way is to use the standard function localtime() or gmtime() and the struct tm.

void loop() {
 time_t now;
 struct tm * timeinfo;
 time(&now);
 timeinfo = localtime(&now); 
 Serial.println(timeinfo->tm_hour);
 delay(1000);
}
answered Jul 23, 2017 at 17:00
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.