用C的库函数获取本地时间

2013-07-22 17:57:22 · 作者: · 浏览: 204

  1. tm结构体

  struct tm {

  int

  tm_sec; /* seconds after the minute [0-60] */

  int tm_min;

  /* minutes after the hour [0-59] */

  int tm_hour;

  /* hours since midnight [0-23] */

  int tm_mday;

  /* day of the month [1-31] */

  int tm_mon;

  /* months since January [0-11] */

  int tm_year;

  /* years since 1900 */

  int tm_wday;

  /* days since Sunday [0-6] */

  int tm_yday;

  /* days since January 1 [0-365] */

  int tm_isdst;

  /* Daylight Savings Time flag */

  long tm_gmtoff;

  /* offset from CUT in seconds */

  char *tm_zone;

  /* timezone abbreviation */

  };

  2. 使用localtime获取本地时间,具体代码如下

  //获取当前时间,采用C的库函数,返回值不需要外部释放,效率方面比使用OC的NSDate类高效3-4倍

  - (struct tm*)getTime

  {

  //时间格式

  struct timeval ticks;

  gettimeofday(&ticks, nil);

  time_t now;

  struct tm* timeNow;

  time(&now);

  timeNow = localtime(&now);

  timeNow->tm_gmtoff = ticks.tv_usec/1000;  //毫秒

  timeNow->tm_year += 1900;    //tm中的tm_year是从1900至今数

  timeNow->tm_mon  += 1;       //tm_mon范围是0-11

  return timeNow;

  }