1 函数原型
localtime():时间类型转换,函数原型如下:
struct tm * localtime (const time_t * timer);
ctime库描述如下:
Convert time_t to tm as local time
1. Uses the value pointed by timer to fill a tm structure with the values that represent the corresponding time, expressed for the local timezone.
- localtime()函数和gmtime()函数都用于将秒数表示的时间转换为更具可读性的时间结构,区别在于:
(1)localtime()函数用于将time_t类型的时间值转换为表示本地时间的时间结构;
(2)gmtime()函数用于将time_t类型的时间值转换为表示UTC时间的时间结构;
(3)本地时间可以通过将UTC时间加上或减去时区偏移量来获得,如北京位于东八区,这意味着北京时间比UTC时间快8个小时,即UTC+8。
2 参数
localtime()函数只有一个参数timer:
- 参数timer是一个指向time_t类型对象的指针,类型为time_t*;timer指向的对象包含要转换的时间值。
ctime库描述如下:
timer
1. Pointer to an object of type time_t that contains a time value.
2. time_t is an alias of a fundamental arithmetic type capable of representing times as returned by function time.
3 参数
localtime()函数的返回值类型为struct tm*类型:
- 转换成功,返回一个指向静态时间结构的指针,该结构包含表示本地时间的日期和时间信息;
- 转换失败,返回NULL。
特别说明
- 静态时间结构是指结构的存储空间在程序开始时分配,并在程序结束时释放,在程序运行期间其生命周期是静态的;
- 同一程序中所有的gmtime()函数和localtime()函数共享同一个静态时间结构,每次调用这两个函数时,都会覆盖这个静态时间结构中的内容;
- 如果要保存静态时间结构中的内容,必须在程序中单独声明一个struct tm类型的时间结构,在每次调用gmtime()函数或localtime()函数后,将静态时间结构中的内容拷贝至新的时间结构中。
ctime库描述如下:
1. A pointer to a tm structure with its members filled with the values that correspond to the local time representation of timer.
2. The returned value points to an internal object whose validity or value may be altered by any subsequent call to gmtime or localtime.
4 示例
4.1 示例1
示例代码如下所示:
int main() {
//
time_t rawtime = 0;