c,c++中时间戳与标准时间间的相互转换

时间:2021-04-04 02:36:25

1,标准时间准换成时间戳

int standard_to_stamp(char *str_time) 

        struct tm stm; 
        int iY, iM, iD, iH, iMin, iS; 

        memset(&stm,0,sizeof(stm)); 
        iY = atoi(str_time); 
        iM = atoi(str_time+5); 
        iD = atoi(str_time+8); 
        iH = atoi(str_time+11); 
        iMin = atoi(str_time+14); 
        iS = atoi(str_time+17); 

        stm.tm_year=iY-1900; 
        stm.tm_mon=iM-1; 
        stm.tm_mday=iD; 
        stm.tm_hour=iH; 
        stm.tm_min=iMin; 
        stm.tm_sec=iS; 

        /*printf("%d-%0d-%0d %0d:%0d:%0d\n", iY, iM, iD, iH, iMin, iS);*/   //标准时间格式例如:2016:08:02 12:12:30
        return (int)mktime(&stm); 


2,时间戳转换成标准时间

typedef struct times
{
        int Year;
        int Mon;
        int Day;
        int Hour;
        int Min;
        int Second;
}Times;

Times stamp_to_standard(int stampTime)
{
        time_t tick = (time_t)stampTime;
        struct tm tm;
        char s[100];
        Times standard;

        //tick = time(NULL);
        tm = *localtime(&tick);
        strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", &tm);
        printf("%d: %s\n", (int)tick, s);


        standard.Year = atoi(s);
        standard.Mon = atoi(s+5);
        standard.Day = atoi(s+8);
        standard.Hour = atoi(s+11);
        standard.Min = atoi(s+14);
        standard.Second = atoi(s+17);
    
        return standard;
}

3,如何获取系统标准时间

time_t rawtime ;

struct tm * timeinfo;

time ( &rawtime );

timeinfo = localtime ( &rawtime );

其中:

int Year = timeinfo->tm_year+1900;

int Mon = timeinfo->tm_mon+1;

其余日,时,分,秒都不变。


4,如何获取系统当前时间戳

 time_t now;                                                                                                                     
 int unixTime = (int)time(&now);