转换为unix时间戳不正确

编程入门 行业动态 更新时间:2024-10-10 21:27:38
本文介绍了转换为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时间戳不正确

本文发布于:2023-11-27 11:21:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637851.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   不正确   时间   unix

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!