C标准时间与时间戳的相互转换
生活随笔
收集整理的這篇文章主要介紹了
C标准时间与时间戳的相互转换
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
什么是時間戳?
- 時間戳是指格林威治時間自1970年1月1日(00:00:00 GTM)至當(dāng)前時間的總秒數(shù)。它也被稱為Unix時間戳(Unix Timestamp)。
- 時間戳是能夠表示一份數(shù)據(jù)在一個特定時間點已經(jīng)存在的完整的可驗證的數(shù)據(jù),通常是一個字符序列,唯一地標(biāo)識某一刻的時間
Demo
#include <stdio.h> #include <string.h> #include <time.h> #include <stdlib.h>/*標(biāo)準(zhǔn)時間轉(zhuǎn)換為時間戳*/ 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);return (int)mktime(&stm);}/*時間戳轉(zhuǎn)換為標(biāo)準(zhǔn)時間*/ 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;tm = *localtime(&tick);strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", &tm);printf("時間戳為:%d 轉(zhuǎn)換成標(biāo)準(zhǔn)時間為: %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; }int main(int argc, char **argv) {int a =0;printf("輸入的標(biāo)準(zhǔn)時間時: %s \n",argv[1]);a=standard_to_stamp(argv[1]);printf("標(biāo)準(zhǔn)時間轉(zhuǎn)換為時間戳: %d\n",a);stamp_to_standard(a); return 0; }運行結(jié)果:
總結(jié)
以上是生活随笔為你收集整理的C标准时间与时间戳的相互转换的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 标准输入输出重定向
- 下一篇: webService上传图片