计算自1970/1/1以来经过了多少时间(精确到毫秒)

标签 c windows

请求接受特定时间并计算自 1970/01/01 00:00:00 以来经过了多少时间 需要考虑毫秒!

例如输入日期时间:2009/08/06 14:35:19.42 结果显示:124958371942

据我所知,time_t 只关心自 1970/01/01 以来经过了多少秒 并且 struct tm 没有要设置的毫秒属性

我尝试使用 mktime 并得到错误的结果:1249540519ll

struct tm t;
t.tm_year = 2009 - 1900;
t.tm_mon = 7;
t.tm_mday = 6;
t.tm_hour = 14;
t.tm_min = 35;
t.tm_sec = 19;

wprintf(L"%ull\n", mktime(&t));

在这种情况下应该使用什么 API? 谢谢!

最佳答案

它出现在 124958371942 中,OP 计算厘秒而不是毫秒。还有一个时区问题。看来 1970 年的时间戳是 UTC 2009 年的日期可能是本地的。

应对时区差异的各种方法。

一种常见的方法是假设 2009/08/06 14:35:19.42 和 1970/01/01 00:00:00 都是世界时。另一个是它们都是本地时间。以下假设均为本地时间。

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

void tt(void) {

  struct tm t = { 0 }; // important to set _all_ fields

  t.tm_year = 2009 - 1900;
  t.tm_mon = 8 - 1;
  t.tm_mday = 6;
  t.tm_hour = 14;
  t.tm_min = 35;
  t.tm_sec = 19;
  t.tm_isdst = -1;  // Unless known let code determine if it is DST or not.
  time_t t1 = mktime(&t);
  printf("%10lld\n", (long long) t1);

  t.tm_year = 1970 - 1900;
  t.tm_mon = 1 - 1;
  t.tm_mday = 1;
  t.tm_hour = 0;
  t.tm_min = 0;
  t.tm_sec = 0;
  t.tm_isdst = -1;
  time_t t0 = mktime(&t);
  printf("%10lld\n", (long long) t0);

  printf("%lf\n", difftime(t1, t0) * 1000.0);
}

// Of course these are per my timezone value
1249587319
     21600
1249565719000.000000

一些细节:

struct tm() 可能 有亚秒字段。这就是为什么将整个结构归零很重要。仅指定了 9 个字段,可能存在其他字段。 tm_wdaytm_yday两个字段在调用mktime()前不需要初始化,但至少要设置其中的7个,包括tm_isdst

difftime() 是减去时间戳的可移植方法。

打印 time_t 时,该值通常是自 1970 年以来没有闰秒的整数秒数。转换为 long long 是一种合理的,但不是绝对可移植的打印方法。

关于计算自1970/1/1以来经过了多少时间(精确到毫秒),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27052964/

相关文章:

c - C中的数组反向输出

c - GSL 的 GCC/MinGW 问题

c++ - 应用程序设置

android - 多个网络 - React Native 在安装 Virtualbox/Vmware 时选择了错误的 ip

c - 我怎样才能简单地在 libtiff 中加载灰度 tiff 并获得像素强度数组?

c - C 中的魔数(Magic Number)

c# - 从 bat 文件运行 Java .jar 和 Windows .exe

windows - 不同服务器的 FTP over CMD

c - 为什么 GCC 在实现整数除法时使用乘以一个奇怪的数字?

c - 我想用c语言将两个不同的结构相乘