dev/c/dtparser_test/File2.cpp

89 lines
2.2 KiB
C++

//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include <tchar.h>
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
#define _XOPEN_SOURCE /* glibc2 needs this */
#include <time.h>
#include <stdio.h>
// òî÷íîå âðåìÿ
struct prec_tm {
struct tm tm; // ñòàíäàðòíûé timestamp
unsigned char ss; // ñàíòèñåêóíäû
};
// òî÷íîå âðåìÿ -> êîë-âî ñàíòèñåêóíä (!!)
int time2ss(struct prec_tm * ptm, __int64 * ss) {
time_t time = mktime(&ptm->tm);
if (time == (time_t)-1) {
fprintf(stderr, "mktime(3) fails with error: can't convert date to time!\n");
return 1;
}
*ss = ((__int64)time) * 100 + ptm->ss;
return 0;
}
// êîë-âî ñàíòèñåêóíä -> òî÷íîå âðåìÿ (!!)
int ss2time(const __int64 * ss, struct prec_tm * ptm) {
time_t time = (*ss)/100;
struct tm * ret = localtime(&time);
if (ret == NULL) {
fprintf(stderr, "localtime_r(3) fails with error: can't convert time to date!\n");
return 1;
}
ptm->tm = *ret;
ptm->ss = (*ss)%100;
return 0;
}
// ñòðîêà -> òî÷íîå âðåìÿ
int str2time(const char * date, struct prec_tm * ptm) {
char *ret = strptime(date, "%d.%m.%Y %T", &ptm->tm);
// ÿ íå ïîíÿë ñòàíäàðòà, âèäèìî îòâåòñòâåííîñòü çà êîððåêòíîñòü âõîäíûõ äàííûõ ëîæèòñÿ íà òîãî, êòî êëàä¸ò...
// if (ret == NULL) {
// fprintf(stderr, "strptime(3) error: can't parse date!\n");
// return 1;
// }
// ptm->tm.tm_year -= 1900;
int len = strlen(date); // ìåäëåííàÿ îïåðàöèÿ, ó ïðèíöèïå...
ptm->ss = atoi(date + len - 2);
return 0;
}
// òî÷íîå âðåìÿ -> ñòðîêà
int time2str(struct prec_tm * ptm, char * buf) {
sprintf(buf, "%.2u.%.2u.%.4u %.2u:%.2u:%.2u.%.2u", ptm->tm.tm_mday, ptm->tm.tm_mon + 1,
ptm->tm.tm_year + 1900, ptm->tm.tm_hour, ptm->tm.tm_min, ptm->tm.tm_sec, ptm->ss);
return 0;
}
int main(void) {
const char date[] = "23.12.2008 10:50:59.36";
char buf[1024];
struct prec_tm ptm;
str2time(date, &ptm);
__int64 ss;
time2ss(&ptm, &ss);
ss2time(&ss, &ptm);
time2str(&ptm, buf);
printf("%s\n", buf);
system("pause");
return 0;
}