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

前端 未结 9 886
臣服心动
臣服心动 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 <time.h>
    #include <stdio.h>
    #include <stdlib.h>    
    
    /*
     *  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);
    }
    
    0 讨论(0)
  • 2020-11-29 06:26

    Here is a solution I use (Can't recall where I found it) when it isn't a windows platform

    time_t _mkgmtime(const struct tm *tm) 
    {
        // Month-to-day offset for non-leap-years.
        static const int month_day[12] =
        {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
    
        // Most of the calculation is easy; leap years are the main difficulty.
        int month = tm->tm_mon % 12;
        int year = tm->tm_year + tm->tm_mon / 12;
        if (month < 0) {   // Negative values % 12 are still negative.
            month += 12;
            --year;
        }
    
        // This is the number of Februaries since 1900.
        const int year_for_leap = (month > 1) ? year + 1 : year;
    
        time_t rt = tm->tm_sec                             // Seconds
            + 60 * (tm->tm_min                          // Minute = 60 seconds
            + 60 * (tm->tm_hour                         // Hour = 60 minutes
            + 24 * (month_day[month] + tm->tm_mday - 1  // Day = 24 hours
            + 365 * (year - 70)                         // Year = 365 days
            + (year_for_leap - 69) / 4                  // Every 4 years is     leap...
            - (year_for_leap - 1) / 100                 // Except centuries...
            + (year_for_leap + 299) / 400)));           // Except 400s.
        return rt < 0 ? -1 : rt;
    }
    
    0 讨论(0)
  • 2020-11-29 06:27

    for those on windows, the below function is available:

    _mkgmtime
    

    link for more info: https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/mkgmtime-mkgmtime32-mkgmtime64

    0 讨论(0)
  • 2020-11-29 06:27

    timegm() works, but is not present on all systems.

    Here's a version that only uses ANSI C. (EDIT: not strictly ANSI C! I'm doing math on time_t, assuming that the units are in seconds since the epoch. AFAIK, the standard does not define the units of time_t.) Note, it makes use of a hack, so-to-speak, to determine the machine's time zone and then adjusts the result from mktime accordingly.

    
    /*
      returns the utc timezone offset
      (e.g. -8 hours for PST)
    */
    int get_utc_offset() {
    
      time_t zero = 24*60*60L;
      struct tm * timeptr;
      int gmtime_hours;
    
      /* get the local time for Jan 2, 1900 00:00 UTC */
      timeptr = localtime( &zero );
      gmtime_hours = timeptr->tm_hour;
    
      /* if the local time is the "day before" the UTC, subtract 24 hours
        from the hours to get the UTC offset */
      if( timeptr->tm_mday < 2 )
        gmtime_hours -= 24;
    
      return gmtime_hours;
    
    }
    
    /*
      the utc analogue of mktime,
      (much like timegm on some systems)
    */
    time_t tm_to_time_t_utc( struct tm * timeptr ) {
    
      /* gets the epoch time relative to the local time zone,
      and then adds the appropriate number of seconds to make it UTC */
      return mktime( timeptr ) + get_utc_offset() * 3600;
    
    }
    
    
    0 讨论(0)
  • 2020-11-29 06:28

    Use timegm() instead of mktime()

    0 讨论(0)
  • 2020-11-29 06:32

    POSIX page for tzset, describes global variable extern long timezone which contains the local timezone as an offset of seconds from UTC. This will be present on all POSIX compliant systems.

    In order for timezone to contain the correct value, you will likely need to call tzset() during your program's initialization.

    You can then just add timezone to the output of mktime to get the output in UTC.

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    time_t utc_mktime(struct tm *t)
    {
        return mktime(t) + timezone;
    } 
    
    int main(int argc, char **argv)
    {
        struct tm t = { 0 };
    
        tzset();
        utc_mktime(&t);
    }
    

    Note: Technically tzset() and mktime() aren't guaranteed to be threadsafe.

    If a thread accesses tzname, [XSI] [Option Start] daylight, or timezone [Option End] directly while another thread is in a call to tzset(), or to any function that is required or allowed to set timezone information as if by calling tzset(), the behavior is undefined.

    ...but the majority of implementations are. GNU C uses mutexes in tzset() to avoid concurrent modifications to the global variables it sets, and mktime() sees very wide use in threaded programs without synchronization. I suspect if one were to encounter side effects, it would be from using setenv() to alter the value of TZ as done in the answer from @liberforce.

    0 讨论(0)
提交回复
热议问题