【问题标题】:How to convert IST time to UTC time in C(Ubuntu)?如何在 C(Ubuntu) 中将 IST 时间转换为 UTC 时间?
【发布时间】:2015-04-23 09:50:30
【问题描述】:

我正在从事 GPS 项目,为此我想在每次接收 gps 数据后添加时间戳(UTC)。如何在 C 中将 IST 转换为 UTC?我从 tv.tv_sec 中减去 5:30 小时,但这不是正确的方法。有什么函数可以从 IST 获取 UTC 吗?

#define MAX_STRING_SIZE          50     /* for TimeStampsForServer */
int fnTimeStampsForGpsData ()
{
        struct timeval tv;
        struct tm *ptm;

        char TimeString[MAX_STRING_SIZE];

        long MicroSeconds;

        /**
         *  Obtain the time of day, and convert it to a tm struct.
         */
        gettimeofday (&tv, NULL);
        tv.tv_sec -= 19800;         /* Number of seconds (5:30) */
        ptm = localtime (&tv.tv_sec);

        /**
         * Format the date and time, down to a single second.
         */
        strftime (TimeString, sizeof (TimeString), "%Y-%m-%d %H:%M:%S", ptm);

        /**
         *  Copying  microseconds.
         */
        MicroSeconds = tv.tv_usec;

        /**
         *  Print the formatted time, in seconds, followed by a decimal point
         *   and the microseconds.
         */
        printf ("%s.%06ld\n", TimeString, MicroSeconds);

        return 0;
}

【问题讨论】:

    标签: c linux ubuntu timezone


    【解决方案1】:

    您可能想查看tzset() 联机帮助页。它记录了一个全局变量 timezone,它类似于调用 tzset() 后您的本地时间(根据您的系统设置)到 GMT 的时区偏移量。

    【讨论】:

      【解决方案2】:

      如果您想将时间戳拆分为 UTC 格式的细分字段,而不是您作为用户当前使用的任何时区,请停止使用 localtime(),改用 gmtime()

      您看,time_t 时间戳始终采用 UTC。 gettimeofday()clock_gettime(CLOCK_REALTIME,)time() 都提供 UTC 时间戳。类型描述本身表示它描述了自 UTC 纪元以来的秒数。

      要将时间戳分解为单独的字段,如果您希望部分采用 UTC,请使用 gmtime(),如果您希望使用当前时区,请使用 localtime()

      您在示例中显然使用了localtime()。那是你问题的根源。因为您(您作为您机器上的登录用户)已经配置了印度时区——它是特定于用户的,而不是特定于机器的——,localtime() 尽职尽责地打破时间,使用印度标准时间规则


      加尔各答是时区数据库中列出的印度人口最多的城市,因此在 C 程序中,您可以使用

      setenv("TZ", ":Asia/Kolkata", 1);
      tzset();
      

      localtime() 和其他适用于当地时间的时间函数将使用印度时区。

      您也可以仅使用命令行来查看其工作原理:

      date
      TZ=:Asia/Kolkata date
      date -u
      TZ=:Asia/Kolkata date -u
      

      -u 标志告诉date 使用 UTC 而不是本地时间输出日期。 (与使用gmtime() 而不是localtime() 相同。)

      由于设置是进程范围的,所以在多线程进程或服务进程中进行设置会稍微复杂一些。服务进程(守护进程)可以使用从属进程进行转换,使用套接字对与 arent 通信(并在套接字关闭时退出,从而在父进程退出时退出)。或者,可以使用互斥锁(例如,pthread_mutex_tmutex)来保护本地时间函数,以便在任何给定时间最多有一个线程依赖于该功能。 (UTC 时间功能不受影响,因此性能损失可能是可以接受的,因为它只会影响本地时间功能。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-03
        • 1970-01-01
        • 2014-05-11
        相关资源
        最近更新 更多