Easy way to convert a struct tm (expressed in UTC) to time_t type

前端 未结 9 925
臣服心动
臣服心动 2020-11-29 05:44

How do I do the above? There is mktime function but that treats the input as expressed in local time but how do i perform the conversion if my input tm variable happens to b

9条回答
  •  自闭症患者
    2020-11-29 06:20

    This is really a comment with code to address the answer by Leo Accend: Try the following:

    #include 
    #include 
    #include     
    
    /*
     *  A bit of a hack that lets you pull DST from your Linux box
     */
    
    time_t timegm( struct tm *tm ) {           // From Leo's post, above
      time_t t = mktime( tm );
      return t + localtime( &t )->tm_gmtoff;
    }
    main()
    {
        struct timespec tspec = {0};
        struct tm tm_struct   = {0};
    
        if (gettimeofday(&tspec, NULL) == 0) // clock_gettime() is better but not always avail
        {
            tzset();    // Not guaranteed to be called during gmtime_r; acquire timezone info
            if (gmtime_r(&(tspec.tv_sec), &tm_struct) == &tm_struct)
            {
                printf("time represented by original utc time_t: %s\n", asctime(&tm_struct));
                // Go backwards from the tm_struct to a time, to pull DST offset. 
                time_t newtime = timegm (&tm_struct);
                if (newtime != tspec.tv_sec)        // DST offset detected
                {
                    printf("time represented by new time_t: %s\n", asctime(&tm_struct));
    
                    double diff = difftime(newtime, tspec.tv_sec);  
                    printf("DST offset is %g (%f hours)\n", diff, diff / 3600);
                    time_t intdiff = (time_t) diff;
                    printf("This amounts to %s\n", asctime(gmtime(&intdiff)));
                }
            }
        }
        exit(0);
    }
    

提交回复
热议问题