在Linux下面編程,經常要碰到用到與time/timestamp相關的東西,下面是我以前收集的,放在這裡共用。
In the file: dbus-sysdeps-unix.c
/** * Get current time, as in gettimeofday(). * * @param tv_sec return location for number of seconds * @param tv_usec return location for number of microseconds (thousandths) */ void _dbus_get_current_time (long *tv_sec, long *tv_usec) { struct timeval t; gettimeofday (&t, NULL); if (tv_sec) *tv_sec = t.tv_sec; if (tv_usec) *tv_usec = t.tv_usec; } |
How to use it:
/** * Get current time, as in gettimeofday(). * * @param tv_sec return location for number of seconds * @param tv_usec return location for number of microseconds (thousandths) */ void _dbus_get_current_time (long *tv_sec, long *tv_usec) { struct timeval t; gettimeofday (&t, NULL); if (tv_sec) *tv_sec = t.tv_sec; if (tv_usec) *tv_usec = t.tv_usec; } |
Two time structures:
Struct timeval:
struct timeval { long tv_sec; long tv_usec; } |
14.11 我知道庫函數 localtime() 可以把 time_t 轉換成結構 struct tm, 而 ctime() 可以把 time_t 轉換成為可列印的字串。怎樣才能進行反向操作, 把 struct tm 或一個字串轉換成 time_t。
ANSI C 提供了庫函數 mktime(), 它把 struct tm 轉換成 time_t。
把一個字串轉換成 time_t 比較難些, 這是由於可能遇到各種各樣的日期和時間格式。某些系統提供函數 strptime(), 基本上是 strftime() 的反向函數。其它常用的函數有 partime() (與