C语言库函数---时间格式转化

时间戳转标准时间

int main(int argc, char **argv)
{
    time_t t;
    t = time(NULL);
    struct tm *lt;
    int ii = time(&t);
    printf("ii = %d\n", ii);
    t = time(NULL);
    lt = localtime(&t);
    char nowtime[24];
    memset(nowtime, 0, sizeof(nowtime));
    strftime(nowtime, 24, "%Y-%m-%d %H:%M:%S", lt);
    printf("nowtime = %s\n", nowtime);
    return 1;
}

打印:

ii = 1325302987
nowtime = 2011-12-31 11:43:07

标准时间转时间戳

随便输入一个标准格式的时间 “2011-12-31 11:43:07”,转换成时间戳 1325302987

#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
 
long GetTick(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);*/
 
    return mktime(&stm);
}
 
int main()
{
    char str_time[19];
 
    printf("请输入时间:"); /*(格式:2011-12-31 11:43:07)*/
 
    gets(str_time);
 
    printf("%ld\n", GetTick(str_time));
 
    return 0;    
}

转:
http://ilewen.com/questions/3990

发布了56 篇原创文章 · 获赞 6 · 访问量 6870

猜你喜欢

转载自blog.csdn.net/qq_23929673/article/details/96422512