时间日期设置--ctime头文件
简述:ctime头文件中的4中与时间相关的数据类型
<ctime>头文件中定义了4种与时间有关的数据类型,如下:
clock_t
size_t
time_t
struct tm
clock_t
Clock type
[时钟类型]
Alias of a fundamental arithmetic type capable of representing clock tick counts.
[clock_t是一个基本算法类型的别名,表示时钟嘀嗒的次数]
Clock ticks are units of time of a constant but system-specific length, as those returned by function clock.
[时钟嘀嗒是时间的单位,它是一个常量,但其长度由系统指定,函数clock()的返回值就是clock_t]
This is the type returned by clock.
[clock_t是函数clock()的返回值]
size_t
Unsigned integral type
[无符号整型]
Alias of one of the fundamental unsigned integer types.
[size_t是无符号整型的别名]
It is a type able to represent the size of any object in bytes: size_t is the type returned by the sizeof operator and is widely used in the standard library to represent sizes and counts.
[size_t表示任何一个对象的字节数,它是sizeof操作数的返回值类型并被广泛应用于标准库中来表示长度和数量]
In <ctime>, it is used in the function strftime as the type of its parameter maxsize and as its return value. In both cases it is used to express counts of characters.
[在<ctime>中,size_t被strftime()函数用作其形参maxsize的参数类型及其返回值类型]
time_t
Time type
[时间类型]
Alias of a fundamental arithmetic type capable of representing times, as those returned by function time.
[time_t是一个基本算法类型的别名,表示时间,函数time()的返回值就是time_t]
For historical reasons, it is generally implemented as an integral value representing the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC (i.e., a unix timestamp). Although libraries may implement this type using alternative time representations.
[由于历史原因,time_t总被实现为一个整数值,表示自UTC时间1970年1月1日0:00:00至今经过的秒数]
Portable programs should not use values of this type directly, but always rely on calls to elements of the standard library to translate them to portable types.
[可移植程序不应该直接使用这种类型的值,而应该通过调用标准库元素将其翻译为可移植类型]
typedef __int64 __time64_t; /* 64-bit time value */
typedef __time64_t time_t; /* time value */
struct tm
Time structure
[时间结构体]
Structure containing a calendar date and time broken down into its components.
[结构体类型tm保存分解为相应元素的日期和时间]
The structure contains nine members of type int (in any order), which are:
[tm保存了9个int型成员,如下:]
Member Type Meaning Range tm_sec int seconds after the minute 0-60* tm_min int minutes after the hour 0-59 tm_hour int hours since midnight 0-23 tm_mday int day of the month 1-31 tm_mon int months since January 0-11 tm_year int years since 1900 tm_wday int days since Sunday 0-6 tm_yday int days since January 1 0-365 tm_isdst int Daylight Saving Time flag
The Daylight Saving Time flag (tm_isdst) is greater than zero if Daylight Saving Time is in effect, zero if Daylight Saving Time is not in effect, and less than zero if the information is not available.
[实行夏令时的时候,tm_isdst为正;不实行夏令时的时候,tm_isdst为0;不了解情况时,tm_isdst为负]
* tm_sec is generally 0-59. The extra range is to accommodate for leap seconds in certain systems.
[*tm_sec通常为0-59,多余的范围是为了在某些系统上适应闰秒]
注:夏令时是一种法定的时间。夏天太阳升起得比较早,白天时间很长,为了节约能源和充分利用白天宝贵的时间,世界上不少国家都采用法律规定的形式,每到夏天就将这个国家使用的时间提前一小时,也有提前半小时或几小时的;到了冬季,又将拨快的时间拨回来。这样的时间就是“夏令时”,是一种法定时间。
/* time_t time (time_t* timer); Get current time Get the current calendar time as a value of type time_t. [该函数返回系统当前日历时间] The function returns this value, and if the argument is not a null pointer, it also sets this value to the object pointed by timer. [如果timer不是空指针,则用timer指向time_t类型的返回值] The value returned generally represents the number of seconds since 00:00 hours, Jan 1, 1970 UTC (i.e., the current unix timestamp). Although libraries may use a different representation of time: Portable programs should not use the value returned by this function directly, but always rely on calls to other elements of the standard library to translate them to portable types (such as localtime, gmtime or difftime). [返回值通常表示的是自UTC时间1970年1月1日00:00:00至今经过的秒数(也就是当前的unix时间戳)。因为库也许会不同的方式表示时间,因此对于可移植程序来说,不应该直接使用该函数的返回值,而应该通过调用标准库中的其他元素来将其翻译为可移植类型(比如调用localtime, gmtime或者difftime)] */ #include <iostream> #include <ctime> int main() { time_t timer; timer = time(NULL); //参数timer为空指针 std::cout<<"自UTC时间1970年1月1日0时0分0秒至今经过的秒数为:"<<timer<<'\n'; time(&timer); //参数timer不为空指针 std::cout<<"自UTC时间1970年1月1日0时0分0秒至今经过的秒数为:"<<timer<<'\n'; system("pause"); return 0; }
/* struct tm * localtime (const time_t * timer); Convert time_t to tm as local time [将time_t转换为保存本地日历时间的结构体tm] Uses the value pointed by timer to fill a tm structure with the values that represent the corresponding time, expressed for the local timezone. [利用指针timer指向的值填充结构体tm,使得tm中保存相对应的本地时区的日期时间]
/////////////////////////////////////////////////////////////////////
char* asctime (const struct tm * timeptr); Convert tm structure to string [将tm结构体转换为字符串string] Interprets the contents of the tm structure pointed by timeptr as a calendar time and converts it to a C-string containing a human-readable version of the corresponding date and time. [将指向tm结构体的timeptr的内容转换为相对应的字符串] The returned string has the following format: [转换之后的字符串形式如下:] Www Mmm dd hh:mm:ss yyyy Where Www is the weekday, Mmm the month (in letters), dd the day of the month, hh:mm:ss the time, and yyyy the year. [其中Www是星期几,Mmm是月,dd是日,hh:mm:ss是时间,yyyy是年] The string is followed by a new-line character ('\n') and terminated with a null-character. [返回的字符串会自动添加一个null作为字符串结束符,还会自动添加一个换行符'\n'] It is defined with a behavior equivalent to: [该函数定义的行为等价于以下操作:] char* asctime(const struct tm *timeptr) { static const char wday_name[][4] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static const char mon_name[][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; static char result[26]; sprintf(result, "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n", wday_name[timeptr->tm_wday], mon_name[timeptr->tm_mon], timeptr->tm_mday, timeptr->tm_hour, timeptr->tm_min, timeptr->tm_sec, 1900 + timeptr->tm_year); return result; } For an alternative with custom date formatting, see strftime. [自定义日期格式,请参看strftime] */ int main() { time_t rawtime; struct tm* timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); std::cout<<"Current local time and date is: "<<asctime(timeinfo); system("pause"); return 0; }
/* char* ctime (const time_t * timer); Convert time_t value to string [将time_t值转换为字符串] Interprets the value pointed by timer as a calendar time and converts it to a C-string containing a human-readable version of the corresponding time and date, in terms of local time. [将指向time_t的timer的内容转换为相对应的字符串] The returned string has the following format: [返回的字符串格式如下:] Www Mmm dd hh:mm:ss yyyy Where Www is the weekday, Mmm the month (in letters), dd the day of the month, hh:mm:ss the time, and yyyy the year. [其中Www是星期几,Mmm是月,dd是日,hh:mm:ss是时间,yyyy是年] The string is followed by a new-line character ('\n') and terminated with a null-character. [返回的字符串会自动添加一个null作为字符串结束符,还会自动添加一个换行符'\n'] This function is equivalent to: [该函数等价于:] asctime(localtime(timer)) For an alternative with custom date formatting, see strftime. [自定义日期格式,请参看strftime] */ #include <iostream> #include <ctime> int main() { time_t rawtime; time(&rawtime); std::cout<<"The current local time is: "<<ctime(&rawtime); system("pause"); return 0; }
/* time_t mktime (struct tm * timeptr); Convert tm structure to time_t [将tm结构体转换为time_t] Returns the value of type time_t that represents the local time described by the tm structure pointed by timeptr (which may be modified). [将tm结构体代表的本地时间转换为time_t格式] This function performs the reverse translation that localtime does. [该函数的作用与localtime()函数的作用恰好相反] The values of the members tm_wday and tm_yday of timeptr are ignored, and the values of the other members are interpreted even if out of their valid ranges (see struct tm). For example, tm_mday may contain values above 31, which are interpreted accordingly as the days that follow the last day of the selected month. [tm结构体中的成员tm_wday和tm_yday会被忽略,其他成员即使其取值超出有效范围也会被进行解释,如果tm_mday可能大于31,但也会被相应地解释为这个月的最后一天] A call to this function automatically adjusts the values of the members of timeptr if they are off-range or -in the case of tm_wday and tm_yday- if they have values that do not match the date described by the other members. [该函数会自动调整tm结构体的值,即使其值超出范围,或者tm_wday及tm_yday与由其他成员所描述出来的日期不匹配] Return Value A time_t value corresponding to the calendar time passed as argument. [返回函数参数所对应的time_t值] If the calendar time cannot be represented, a value of -1 is returned. [如果不能把信息表示为合法日历,则返回-1] */ #include <iostream> #include <ctime> int main() { time_t rawtime; struct tm* timeinfo; int year, month, day; const char* weekday[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; std::cout<<"Enter year: "; std::cin>>year; std::cout<<"Enter month: "; std::cin>>month; std::cout<<"Enter day: "; std::cin>>day; time(&rawtime); timeinfo = localtime(&rawtime); timeinfo->tm_year = year-1900; timeinfo->tm_mon = month-1; timeinfo->tm_mday = day; /* call mktime: timeinfo->tm_wday will be set */ mktime(timeinfo); std::cout<<"That day is a "<<weekday[timeinfo->tm_wday]<<'\n'; system("pause"); return 0; }
/* size_t strftime (char* ptr, size_t maxsize, const char* format, const struct tm* timeptr ); Format time as string [将tm结构体格式化为字符串] Copies into ptr the content of format, expanding its format specifiers into the corresponding values that represent the time described in timeptr, with a limit of maxsize characters. [将tm结构体的参数按参数format所设定的格式进行格式化,并将格式化后的结果放到字符串ptr中(至多maxsize个字符)] maxsize Maximum number of characters to be copied to ptr, including the terminating null-character. [拷贝到ptr中的最大字符数目,包括null结束符] Return Value If the length of the resulting C string, including the terminating null-character, doesn't exceed maxsize, the function returns the total number of characters copied to ptr (not including the terminating null-character). Otherwise, it returns zero, and the contents of the array pointed by ptr are indeterminate. [如果字符串ptr的长度(包括null结束符)没有超过maxsize,则该函数返回字符串ptr中字符的个数(不包括null结束符);否则返回0,且ptr的内容未定义] format 用于设定格式的说明符如下: specifier Replaced by Example %a Abbreviated weekday name * Thu %A Full weekday name * Thursday %b Abbreviated month name * Aug %B Full month name * August %c Date and time representation * Thu Aug 23 14:55:02 2001 %C Year divided by 100 and truncated to integer (00-99) 20 %d Day of the month, zero-padded (01-31) 23 %D Short MM/DD/YY date, equivalent to %m/%d/%y 08/23/01 %e Day of the month, space-padded ( 1-31) 23 %F Short YYYY-MM-DD date, equivalent to %Y-%m-%d 2001-08-23 %g Week-based year, last two digits (00-99) 01 %G Week-based year 2001 %h Abbreviated month name * (same as %b) Aug %H Hour in 24h format (00-23) 14 %I Hour in 12h format (01-12) 02 %j Day of the year (001-366) 235 %m Month as a decimal number (01-12) 08 %M Minute (00-59) 55 %n New-line character ('\n') %p AM or PM designation PM %r 12-hour clock time * 02:55:02 pm %R 24-hour HH:MM time, equivalent to %H:%M 14:55 %S Second (00-61) 02 %t Horizontal-tab character ('\t') %T ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S 14:55:02 %u ISO 8601 weekday as number with Monday as 1 (1-7) 4 %U Week number with the first Sunday as the first day of week one (00-53) 33 %V ISO 8601 week number (00-53) 34 %w Weekday as a decimal number with Sunday as 0 (0-6) 4 %W Week number with the first Monday as the first day of week one (00-53) 34 %x Date representation * 08/23/01 %X Time representation * 14:55:02 %y Year, last two digits (00-99) 01 %Y Year 2001 %z ISO 8601 offset from UTC in timezone (1 minute=1, 1 hour=100) +100If timezone cannot be termined, no characters
%Z Timezone name or abbreviation * CDT If timezone cannot be termined, no characters %% A % sign % * The specifiers marked with an asterisk (*) are locale-dependent. */ #include <iostream> #include <ctime> int main() { time_t timer; struct tm* timeinfo; char buffer[80]; time(&timer); timeinfo = localtime(&timer); strftime(buffer, 80, "Now it's %I:%M%p", timeinfo); std::cout<<buffer<<'\n'; system("pause"); return 0; }
/* struct tm * gmtime (const time_t * timer); Convert time_t to tm as UTC time [将time_t转换为tm格式的UTC时间] Uses the value pointed by timer to fill a tm structure with the values that represent the corresponding time, expressed as a UTC time (i.e., the time at the GMT timezone). [将指向time_t的指针timer的内容转换为对应的UTC时间] For a local time alternative, see localtime. [如果想要转换成本地时间,请看localtime] */ #include <iostream> #include <ctime> #define MST (-7) #define UTC (0) #define CCT (+8) int main () { time_t rawtime; struct tm * ptm; time(&rawtime); ptm = gmtime(&rawtime); std::cout<<"Current time around the World:\n"; std::cout<<"Phoenix, AZ (U.S.) : "<<(ptm->tm_hour+MST)%24<<":"<<ptm->tm_min<<'\n'; std::cout<<"Reykjavik (Iceland) : "<< (ptm->tm_hour+UTC)%24<<":"<<ptm->tm_min<<'\n'; std::cout<<"Beijing (China) : "<< (ptm->tm_hour+CCT)%24<<":"<<ptm->tm_min<<'\n'; system("pause"); return 0; }
/* clock_t clock (void); Clock program Returns the processor time consumed by the program. [返回自程序开始运行的处理器时间] The value returned is expressed in clock ticks, which are units of time of a constant but system-specific length (with a relation of CLOCKS_PER_SEC clock ticks per second). [该函数的返回值使用时钟嘀嗒数来表示,时钟嘀嗒是时间的单位,它是一个常量,但其长度由系统决定(时钟嘀嗒数除以CLOCKS_PER_SEC即转换为秒数)] The epoch used as reference by clock varies between systems, but it is related to the program execution (generally its launch). To calculate the actual processing time of a program, the value returned by clock shall be compared to a value returned by a previous call to the same function. [不同时代的系统时钟不一样,但时钟与程序运行时间相关,如果要计算程序运行的实际时间,应该计算两个时钟嘀嗒数的差值] */ #include <iostream> #include <ctime> #include <cmath> int frequency_of_primes (int n){ //求1-n之间素数的个数 int i, j; int freq = n-1; //因为1不是素数,因此freq最大为n-1个 for(i=2; i<=n; i++) for(j=sqrt(double(i)); j>1; j--) if(i%j == 0) { --freq; break; } return freq; } int main() { clock_t t; int f; t = clock(); std::cout<<"Calculating...\n"; f = frequency_of_primes(99999); std::cout<<"The number of primes lower than 100,000 is: "<<f<<'\n'; t = clock() - t; std::cout<<"It took me "<<t<<" clicks ("<<(float)t/CLOCKS_PER_SEC<<" seconds)"<<'\n'; system("pause"); return 0; }
/* double difftime (time_t end, time_t beginning); Return difference between two times [返回时间差] Calculates the difference in seconds between beginning and end. [计算beginning和end之间相差的秒数] */ #include <iostream> #include <ctime> int main() { time_t now; struct tm newyear; double seconds; time(&now); newyear = *localtime(&now); newyear.tm_hour = newyear.tm_hour-1; seconds = difftime(now, mktime(&newyear)); std::cout<<seconds<<" seconds since new year in the current timezone.\n"; system("pause"); return 0; }