Converting string containing localtime into UTC in C

前端 未结 3 1912
长发绾君心
长发绾君心 2021-01-13 09:12

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\";
st         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-13 09:55

    Here's my version, using tm_gmtoff. Hopefully, the library takes care of daylight savings time ...

    #define _BSD_SOURCE
    #define _XOPEN_SOURCE
    #include 
    #include 
    
    int gmtoffset(void) {
      struct tm *dummy;
      time_t t = 0;
      dummy = localtime(&t);
      return dummy->tm_gmtoff; /* _BSD_SOURCE */
    }
    
    int main(void) {
      int off;
      const char *date = "2009/09/01/00";
      struct tm cal = {0};
      time_t t;
    
      off = gmtoffset();
    
      strptime(date, "%Y/%m/%d/%H", &cal); /* _XOPEN_SOURCE */
      t = mktime(&cal);
      printf("t     --> %s", ctime(&t)); /* ctime includes a final '\n' */
      t -= off;
      printf("t-off --> %s", ctime(&t));
      return 0;
    }
    
    $ /usr/bin/gcc ptime.c
    
    $ ./a.out
    t     --> Tue Sep  1 01:00:00 2009
    t-off --> Tue Sep  1 00:00:00 2009
    

提交回复
热议问题