如何在 C 中从 NTP 服务器设置 UTC 时间

How to setup UTC time from NTP server in C

我想要这种格式的时间:"t":"2020-03-06T12:09:38.000Z"。如何在 C 中做到这一点??

我尝试了以下代码从 NTP 获取时间,但它对我不起作用。

源代码:

// Get time From NTP and setup in SDK format
String GetTime(){                        // Setup UCT time from NTP server
    String Y,M,D1,D2,Ti;
    time_t now = time(nullptr);
    String T= (ctime(&now));
    //Serial.println(T);
    if (T.substring(20,22) == "20") {
        D1 = T.substring(8,9);          if (D1 == " ")D1 = "0";
        D2 = T.substring(9,10);
        M = Months(T.substring(4,7));   Y = T.substring(20,24);
        Ti = T.substring(11,19);
        return (Y+"-"+M+"-"+D1+D2+"T"+Ti+".000Z");
    }
      return (Y+"-"+M+"-"+D1+D2+"T"+Ti+".000Z");
}

它显示成员子字符串和操作数 + 错误。

谢谢

在 C 中,您可以使用 strftime 但您的代码不是 C 代码。

/* strftime example */
#include <stdio.h>      /* puts */
#include <time.h>       /* time_t, struct tm, time, localtime, strftime */

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;
  char buffer [80];

  time (&rawtime);
  timeinfo = localtime (&rawtime);

  strftime (buffer,80,"%Y-%m-%dT%H:%M:%S.000Z",timeinfo);
  puts (buffer);

  return 0;
}

来源:http://www.cplusplus.com/reference/ctime/strftime/

How to setup UTC time from NTP server in C

I tried below code to get time from NTP, but it not working for me.

OP 发布的代码在本地时间形成一个字符串,而不是 UTC,因为 ctime() 就像 asctime(localtime(timer))

代码应使用 gmtime(const time_t *timer); 表示 UTC。

存在字符串管理问题。在C中,最好提供缓冲区。

要形成类似 ISO 8601 的时间戳,请使用 strftime()

  • %F 相当于“%Y-%m-%d”(ISO 8601 日期格式)。 [tm_year、tm_mon、tm_mday]
  • %T 相当于“%H:%M:%S”(ISO 8601 时间格式)。 [tm_hour, tm_min, tm_sec]

要访问 sub-second 单元需要实现特定代码。下面的示例代码使用 ".000".

开始 OP 的一些示例代码。

#include <stdio.h>
#include <time.h>

char* ISO8601(size_t sz, char dest[sz], time_t t) {
  struct tm *tm = gmtime(&t);
  if (tm == NULL) {
    return NULL;
  }

  if (strftime(dest, sz, "%FT%T.000Z", tm) == 0) {
    return NULL;
  }
  return dest;
}

int main(void) {
  char buf[100];
  char *s = ISO8601(sizeof buf, buf, time(NULL));
  if (s) {
    puts(s);
  }
}

输出

2020-08-25T08:19:42.000Z