how to get datetime from gettimeofday in C?

Colin picture Colin · May 2, 2017 · Viewed 7.8k times · Source

how to get datetime from gettimeofday in C? I need convert tv.tv_sec to Hour:Minute:Second xx without functions such as localtime and strftime ..., just get it by computing. for instance tv.tv_sec/60)%60 will be minute

#include <stdio.h>
#include <time.h>
#include<sys/time.h>

int main ()
{
  struct  timeval tv;
  struct  timezone   tz;
  gettimeofday(&tv,&tz);
  printf("TimeZone-1=%d\n", tz.tz_minuteswest);
  printf("TimeZone-2=%d\n", tz.tz_dsttime);
  printf("TimeVal-3=%d\n", tv.tv_sec);
  printf("TimeVal-4=%d\n", tv.tv_usec);
  printf ( "Current local time and date: %d-%d\n", (tv.tv_sec%    (24*60*60)/3600,tz.tz_minuteswest);

    return 0;
  }

how to get the current Hour of system by computing tv and tz, also to get Minute, Second and MS ~

Answer

chux - Reinstate Monica picture chux - Reinstate Monica · May 2, 2017

Assumption: time_t is seconds since the beginning of a day - universal time. This is commonly Jan 1, 1970 UTC of which the code is assumed to be using given sys/time.h

The main idea is to extract from each member of tv,tz the data to form local time. Time-of-day , UTC, in seconds from tv.tv_sec, minutes from timezone offset and hour adjustment per DST flag. Lastly, insure the result is in the primary range.

Various type concerns include the fields of tv are not specified as int.

Avoid using magic numbers like 60. SEC_PER_MIN self-documents the code.

#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#define SEC_PER_DAY   86400
#define SEC_PER_HOUR  3600
#define SEC_PER_MIN   60

int main() {
  struct timeval tv;
  struct timezone tz;
  gettimeofday(&tv, &tz);
  printf("TimeZone-1 = %d\n", tz.tz_minuteswest);
  printf("TimeZone-2 = %d\n", tz.tz_dsttime);
  // Cast members as specific type of the members may be various 
  // signed integer types with Unix.
  printf("TimeVal-3  = %lld\n", (long long) tv.tv_sec);
  printf("TimeVal-4  = %lld\n", (long long) tv.tv_usec);

  // Form the seconds of the day
  long hms = tv.tv_sec % SEC_PER_DAY;
  hms += tz.tz_dsttime * SEC_PER_HOUR;
  hms -= tz.tz_minuteswest * SEC_PER_MIN;
  // mod `hms` to insure in positive range of [0...SEC_PER_DAY)
  hms = (hms + SEC_PER_DAY) % SEC_PER_DAY;

  // Tear apart hms into h:m:s
  int hour = hms / SEC_PER_HOUR;
  int min = (hms % SEC_PER_HOUR) / SEC_PER_MIN;
  int sec = (hms % SEC_PER_HOUR) % SEC_PER_MIN; // or hms % SEC_PER_MIN

  printf("Current local time: %d:%02d:%02d\n", hour, min, sec);
  return 0;
}

Output sample

TimeZone-1 = 360
TimeZone-2 = 1
TimeVal-3  = 1493735463
TimeVal-4  = 525199
Current local time: 9:31:03