我写了一个函数,它根据时间,日期和时区输入创建一个time_t。该功能在Linux甚至Solaris上都能正常运行。但我在Windows 7上的Cygwin中表达了一种奇怪的行为。在Cygwin中,它为每次测试打印相同的时间。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
time_t create_time( const char* time_s, const char* date_s, const char* zone_s ) {
time_t now;
char *old_tz;
struct tm *comptime;
int x, y, z;
time( &now );
old_tz = getenv( "TZ" );
if ( setenv("TZ", zone_s, 1) ) {
printf( "Can't set environment variable TZ to %s\n", zone_s );
return (time_t)(-1);
}
comptime = localtime( &now );
if ( time_s ) {
if ( 2 == sscanf(time_s, "%d:%d", &x, &y) ) {
comptime->tm_hour = x;
comptime->tm_min = y;
}
else {
return (time_t)(-1);
}
}
if ( date_s ) {
if ( 3 == sscanf( date_s, "%d-%d-%d", &x, &y, &z ) ) {
comptime->tm_year = x-1900;
comptime->tm_mon = y-1;
comptime->tm_mday = z;
}
else {
return (time_t)(-1);
}
}
comptime->tm_sec = 0;
now = mktime( comptime );
if ( old_tz ) setenv( "TZ", old_tz, 1 );
else unsetenv( "TZ" );
return now;
}
int main( int argc, char** argv ) {
char buffer1[32];
char buffer2[32];
char buffer3[32];
char *time_s;
char *date_s;
char *zone_s;
int offset;
time_t rawtime;
time( &rawtime );
printf( "Local time: %s", asctime( localtime(&rawtime) ) );
printf( "GMT time: %s", asctime( gmtime(&rawtime) ) );
/* Test first version */
puts("\nTest 1");
strcpy( buffer1, "11:30" );
strcpy( buffer2, "2011-01-07" );
strcpy( buffer3, "CET" );
offset = 60;
time_s = buffer1;
date_s = buffer2;
zone_s = buffer3;
printf( "Input: %s %s %s\n", date_s, time_s, zone_s );
rawtime = create_time( time_s, date_s, zone_s );
if ( (time_t)(-1) == rawtime ) {
strcpy( buffer1, "Error in time expression\n" );
}
else {
strcpy( buffer1, ctime(&rawtime) );
}
printf( "Local time (%s): %s", zone_s, buffer1 );
/* Test second version */
puts("\nTest 2");
strcpy( buffer1, "11:30" );
strcpy( buffer2, "2011-01-07" );
strcpy( buffer3, "GMT" );
printf( "Input: %s %s %s\n", date_s, time_s, zone_s );
rawtime = create_time( time_s, date_s, zone_s );
if ( (time_t)(-1) == rawtime ) {
strcpy( buffer1, "Error in time expression\n" );
}
else {
strcpy( buffer1, ctime(&rawtime) );
}
printf( "Local time (%s): %s", zone_s, buffer1 );
return 0;
}
你知道什么可能导致这种(误)行为吗?
此致
马丁。
答案 0 :(得分:0)
Windows本地将本地时间放在任何地方(Cygwin跟随它),除非您明确询问UTC时间。这不是你的错误行为,你的代码是正确的。您可以谷歌了解更多详情。
作为方向,您可以尝试深入了解... python(java,ruby,php,....)的源代码,以检查它是如何在那里做出正确决定的。