转换为unix时间戳不正确 [英] Conversion to unix timestamp incorrect

查看:186
本文介绍了转换为unix时间戳不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个编写的函数(如果有很好的标准替代品,请告诉我...)

I have a function that I wrote (if there is a good standard substitute, please let me know...)

time_t get_unix_time(string time_str) {
    time_t loctime;
    time(&loctime);

    struct tm *given_time;
    time_str = time_str.substr(0, time_str.find_first_of('.'));

    replace(time_str.begin(), time_str.end(), ':', ',');
    replace(time_str.begin(), time_str.end(), '-', ',');
    replace(time_str.begin(), time_str.end(), '/', ',');
    replace(time_str.begin(), time_str.end(), ' ', ',');

    given_time = localtime(&loctime);
    vector<string> trecord = split_string(time_str, ',');

    given_time->tm_year = atoi(trecord.at(0).c_str()) - 1900;
    given_time->tm_mon  = atoi(trecord.at(1).c_str()) - 1;
    given_time->tm_mday = atoi(trecord.at(2).c_str());
    given_time->tm_hour = atoi(trecord.at(3).c_str());
    given_time->tm_min  = atoi(trecord.at(4).c_str());
    given_time->tm_sec  = atoi(trecord.at(5).c_str());

    return mktime(given_time);
}

该函数的输入(time_str)格式为 1970-01-01 00:00:00.0 . split_string()函数将字符串time_str拆分为一个包含以下内容的向量:

The input (time_str) to the function is of the format 1970-01-01 00:00:00.0. The split_string() function splits the string time_str into a vector containing:

{1970,01,01,00,00,00}

{ 1970, 01, 01, 00, 00, 00 }

用于填写给定的时间结构.

which is used to fill in the given_time structure.

我编写了一个函数对其进行测试,并将其准确地传递给该输入(纪元的开始).但是,它带给我的时间是21600,即 1970-01-01 06:00:00 UTC + 6 .预期的输出是 0 (时期的开始).

I wrote a function to test it, and passed it exactly that input (start of epoch). However, the time it gives me back is 21600, which is 1970-01-01 06:00:00, or UTC+6. The expected output is 0 (start of the epoch).

注意:我在美国中部时区,即UTC-6.在CST 1970年1月1日午夜,UTC时间是1970年1月1日06:00:00.

我的功能中是否有任何特定于我的时区的内容?我在此功能中做错了吗,还是可以做一些不同的事情以使其独立于区域,或者至少始终是UTC.

Is there anything in my function that is making it specific to my timezone? Am I doing something wrong in this function, or can I do something different to make it zone independent, or at least always UTC.

推荐答案

如果您使用的是 glibc 您可以使用timegm函数,它是mktime的一个版本,始终将时间解释为好像在GMT时区中.不幸的是,该函数的文档基本上声明不能使用标准库调用来实现.因此,除非您有运气,否则您有点不走运.

If you are using glibc you have the timegm function at your disposal, which is a version of mktime that always interprets the time as if it were in the GMT timezone. Unfortunately, the documentation for that function basically states that it cannot otherwise be implemented using standard library calls. So you're sort of out of luck unless you have it.

这篇关于转换为unix时间戳不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆