Time_Calculator
March 11, 2018
系统 time函数实现
#define _CRT_SECURE_NO_WARNINGS //使用了VS2017认为unsafe的函数 #include <iostream> #include <ctime> #include <conio.h> #include <cstring> using namespace std; struct tj_time { int tj_year; //表示年份 int tj_month; //表示月(1-12) int tj_day; //表示日(1-28/29/30/31) int tj_hour; //表示小时(0-23) int tj_minute; //表示分(0-59) int tj_second; //表示秒(0-59) }; void wait_for_enter(const char *prompt = "") //功 能:给出提示并等待回车键 { if (strlen(prompt) == 0) cout << endl << "按回车键继续"; else cout << endl << prompt << ",按回车键继续"; while (_getch() != '\r') ; cout << endl << endl; } void system_time_output(const time_t input_time) //功 能:调用系统的转换函数将整型秒值转换为与此相似的结构体并输出 { //time_t的本质是64位无符号整数 struct tm *tt; //struct tm 为系统定义的结构体 tt = localtime(&input_time); //localtime为系统函数 // tm_*** 为struct tm中的成员,和struct tj_time的内容不完全符合,具体请自行查找相关资料 cout << tt->tm_year + 1900 << '-' << tt->tm_mon + 1 << '-' << tt->tm_mday << ' ' << tt->tm_hour << ':' << tt->tm_min << ':' << tt->tm_sec << endl; return; } void tj_time_output(struct tj_time *tp) // 实现自定义结构的输出,输出形式与system_time_output相同 { cout << tp->tj_year << '-' << tp->tj_month << '-' << tp->tj_day << ' ' << tp->tj_hour << ':' << tp->tj_minute << ':' << tp->tj_second << endl; } struct tj_time *tj_time_convert(int input_time) //功 能:自定义转换函数 { static struct tj_time result; //定义静态局部变量 int mon[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 }; result.tj_year = 1970, result.tj_month = result.tj_day = 1, result.tj_hour = result.tj_minute = result.tj_second = 0; int day, i; day = input_time / (24 * 60 * 60); input_time %= (24 * 60 * 60); result.tj_hour = input_time / (60 * 60); input_time %= (60 * 60); result.tj_hour += 8; //东8区 if (result.tj_hour >= 24) { day++; result.tj_hour %= 24; } result.tj_minute = input_time / 60; input_time %= 60; result.tj_second = input_time; for (i = 1; i <= day; i++) { if ((result.tj_year % 4 == 0 && result.tj_year % 100 != 0) || (result.tj_year % 400 == 0)) mon[2] = 29; else mon[2] = 28; result.tj_day++; if (result.tj_day == mon[result.tj_month] + 1) { result.tj_month++; result.tj_day = 1; } if (result.tj_month == 13) { result.tj_year++; result.tj_month = 1; result.tj_day = 1; } } return &result; //返回静态局部变量地址 } int main() { int test_time[] = { 1, 123456789, 349823021, 987654321, 1202990407, 1216468807, 1250312143, 1272636353, 1326193524, 1336549496, 1392837128, 1625675376, 2052743737 }; int i; struct tj_time *tp; for (i = 0; i < sizeof(test_time) / sizeof(int); i++) { cout << "秒数 :" << test_time[i] << endl; cout << "系统转换的结果 :"; system_time_output(test_time[i]); cout << "自定义转换的结果:"; tp = tj_time_convert(test_time[i]); tj_time_output(tp); wait_for_enter(); } if (1) { struct tj_time *tp; int t = (int)time(0); //系统函数,取当前系统时间(从1970-01-01 00:00:00开始的秒数) cout << "当前系统时间 :" << t << endl; cout << "系统转换的结果 :"; system_time_output(t); cout << "自定义转换的结果:"; tp = tj_time_convert(t); tj_time_output(tp); wait_for_enter(); } return 0; }