将含有本地时间字符串转换成UTC使用C [英] Converting string containing localtime into UTC in C
问题描述
我有一个包含本地日期/时间的字符串,我需要将其转换为一个time_t的值(UTC) - 我一直想这样的:
I have a string containing a local date/time and I need to convert it to a time_t value (in UTC) - I've been trying this:
char* date = "2009/09/01/00";
struct tm cal = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL};
strptime(date, "%Y/%m/%d/%H", &cal);
time_t t = mktime(&cal);
但time_t的值,我得到的回复是,如果字符串正在解析为UTC而不是本地时间,我期望的值。也许我误解了应该怎样strptime做的,但在我的9月1日时区(英国),我们使用的是BST(即UTC + 1小时),所以我期望我最终的价值是比UTC的1小时
but the time_t value I get back is the value that I would expect if the string was being parsed as UTC not local time. Maybe I have misunderstood what strptime is supposed to do, but in my timezone (UK) on the 1st September we are using BST (ie UTC + 1 hour) so I would expect the value I end up with to be 1 hour ahead of UTC.
有没有办法来间preT字符串作为本地时间,自动考虑到UTC偏移会一直在该日起?请注意,我需要的time_t的值不是一个结构TM,在上面的例子我想time_t的值对应于2009-09-01 01:00:00 GMT
Is there a way to interpret the string as localtime, automatically taking into account the UTC offset that would have been in effect on that date? Note that I need the time_t value not a struct tm, in the example above I want the time_t value to correspond to 2009-09-01 01:00:00 GMT
推荐答案
我想我现在已经破解了,这要感谢Andomar - 这code做什么,我需要的,似乎不管工作的当前状态DST(我改变了我的电脑上的时钟进行检查):
I think I've cracked it now, thanks to Andomar - this code does what I need and appears to work regardless of the current DST status (I changed the clock on my PC to check this):
#include <time.h>
#include <assert.h>
time_t parseLocalDate(char* date){
struct tm cal = {0, 0, 0, 0, 0, 0, 0, 0, -1, 0, NULL};
strptime(date, "%Y/%m/%d/%H", &cal);
return mktime(&cal);
}
int main(int argc, char *argv[]){
// DST is effect, Local Time = GMT+1
assert(1251759600 == parseLocalDate("2009/09/01/00")); // Mon, 31 Aug 2009 23:00:00 GMT
assert(1254351600 == parseLocalDate("2009/10/01/00")); // Wed, 30 Sep 2009 23:00:00 GMT
// DST not in effect, Local Time = GMT
assert(1257033600 == parseLocalDate("2009/11/01/00")); // Sun, 01 Nov 2009 00:00:00 GMT
}
这篇关于将含有本地时间字符串转换成UTC使用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!