time时间处理

time时间处理

linux环境下,对时间处理

// gcc tm.c

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


/*
 * 字符串转换成时间戳
 * 输入格式 : 2024-06-06 18:38:20
 */
time_t string_to_timestamp(char * time_str) {
    struct tm tm_info = {0} ;
    if( sscanf( time_str, "%4d-%2d-%2d %2d:%2d:%2d", &tm_info.tm_year, &tm_info.tm_mon, &tm_info.tm_mday, &tm_info.tm_hour, &tm_info.tm_min, &tm_info.tm_sec ) != 6 ) {
        return (time_t) -1;
    }
    tm_info.tm_year -= 1900 ;
    tm_info.tm_mon -= 1 ;

    time_t timestamp = mktime(&tm_info) ;

    return timestamp ;
}


/*
 * 时间戳转换成字符串
 * 输出格式 : 2024-06-06 18:38:20
 */
int timestamp_to_string(char * date_s, int size, time_t itm) {
    struct tm * timeinfo ;

    // localtime 和 localtime_r 都可以处理
    // timeinfo = localtime(&itm) ;  // 返回全局变量,并发需要上锁
    // strftime(date_s, size, "%Y-%m-%d %H:%M:%S", timeinfo) ;

    struct tm tm_result = {0};
    timeinfo = localtime_r(&itm, &tm_result);  // 返回全局变量,并发需要上锁
    strftime(date_s, size, "%Y-%m-%d %H:%M:%S", timeinfo) ;

    return 0 ;
}

int main() {
    char local_time[30] ;

    time_t cur_t = time(NULL);
    memset(local_time, 0x00, sizeof(local_time)) ;

    timestamp_to_string(local_time, sizeof(local_time), cur_t) ;
    printf("now is [ %s ]\n", local_time) ;

    time_t rslt_tm = string_to_timestamp(local_time) ;
    printf("rslt_tm [ %ld ]\n", rslt_tm ) ;

    return 0 ;
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注