【问题标题】:How to setup UTC time from NTP server in C [closed]如何从 C 中的 NTP 服务器设置 UTC 时间 [关闭]
【发布时间】:2020-08-25 07:34:34
【问题描述】:

我想要这种格式的时间:"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 还是 C#? C 不是 C#。
  • 这不是 C 代码
  • 您能否详细说明您的代码“不起作用”的原因?你期待什么,实际发生了什么?如果您遇到异常/错误,请发布它发生的行以及可以使用minimal reproducible example 完成的异常/错误详细信息。请edit您的问题将这些详细信息添加到其中,否则我们可能无法提供帮助。
  • 如何将 C# 代码转换为 C 代码??
  • 我想要 (t":"2020-03-06T12:09:38.000Z) 这种格式的日期和时间。还有其他方法吗?

标签: c utc


【解决方案1】:

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

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

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]

要访问亚秒级单位需要特定于实现的代码。下面的示例代码使用".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

【讨论】:

  • 谢谢你;)它工作
  • 如何更改 .000Z (.mmmz) 以显示随机值? (在你的代码 000Z 常量右边)
  • @vasim sprintf(strchr(buf, '.'), "%.03uZ", rand()%1000u); 可能会起作用。
【解决方案2】:

在 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/

【讨论】:

  • 你能给我一个示例代码来打印 (t":"2020-03-06T12:09:38.000Z) 这种格式。
  • 我编辑我的回复
  • 谢谢。我改变了我的帖子
  • 谢谢,我尝试了这两个代码。两者都在工作
猜你喜欢
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多