您的位置:首页 > 其它

时间日期设置--ctime头文件

2015-07-09 21:45 357 查看
简述:ctime头文件中的4中与时间相关的数据类型

<ctime>头文件中定义了4种与时间有关的数据类型,如下:
clock_t
size_t
time_t
structtm

clock_t
Clocktype
[时钟类型]
Aliasofafundamentalarithmetictypecapableofrepresentingclocktickcounts.
[clock_t是一个基本算法类型的别名,表示时钟嘀嗒的次数]
Clockticksareunitsoftimeofaconstantbutsystem-specificlength,asthosereturnedbyfunctionclock.
[时钟嘀嗒是时间的单位,它是一个常量,但其长度由系统指定,函数clock()的返回值就是clock_t]
Thisisthetypereturnedbyclock.
[clock_t是函数clock()的返回值]

size_t
Unsignedintegraltype
[无符号整型]
Aliasofoneofthefundamentalunsignedintegertypes.
[size_t是无符号整型的别名]
Itisatypeabletorepresentthesizeofanyobjectinbytes:size_tisthetypereturnedbythesizeofoperatorandiswidelyusedinthestandardlibrarytorepresentsizesandcounts.
[size_t表示任何一个对象的字节数,它是sizeof操作数的返回值类型并被广泛应用于标准库中来表示长度和数量]
In<ctime>,itisusedinthefunctionstrftimeasthetypeofitsparametermaxsizeandasitsreturnvalue.Inbothcasesitisusedtoexpresscountsofcharacters.
[在<ctime>中,size_t被strftime()函数用作其形参maxsize的参数类型及其返回值类型]

time_t
Timetype
[时间类型]
Aliasofafundamentalarithmetictypecapableofrepresentingtimes,asthosereturnedbyfunctiontime.
[time_t是一个基本算法类型的别名,表示时间,函数time()的返回值就是time_t]
Forhistoricalreasons,itisgenerallyimplementedasanintegralvaluerepresentingthenumberofsecondselapsedsince00:00hours,Jan1,1970UTC(i.e.,aunixtimestamp).Althoughlibrariesmayimplementthistypeusingalternativetimerepresentations.
[由于历史原因,time_t总被实现为一个整数值,表示自UTC时间1970年1月1日0:00:00至今经过的秒数]
Portableprogramsshouldnotusevaluesofthistypedirectly,butalwaysrelyoncallstoelementsofthestandardlibrarytotranslatethemtoportabletypes.
[可移植程序不应该直接使用这种类型的值,而应该通过调用标准库元素将其翻译为可移植类型]
typedef__int64__time64_t;/*64-bittimevalue*/
typedef__time64_ttime_t;/*timevalue*/

structtm
Timestructure
[时间结构体]
Structurecontainingacalendardateandtimebrokendownintoitscomponents.
[结构体类型tm保存分解为相应元素的日期和时间]
Thestructurecontainsninemembersoftypeint(inanyorder),whichare:
[tm保存了9个int型成员,如下:]

MemberTypeMeaningRange
tm_secintsecondsaftertheminute0-60*
tm_minintminutesafterthehour0-59
tm_hourinthourssincemidnight0-23
tm_mdayintdayofthemonth1-31
tm_monintmonthssinceJanuary0-11
tm_yearintyearssince1900
tm_wdayintdayssinceSunday0-6
tm_ydayintdayssinceJanuary10-365
tm_isdstintDaylightSavingTimeflag


TheDaylightSavingTimeflag(tm_isdst)isgreaterthanzeroifDaylightSavingTimeisineffect,zeroifDaylightSavingTimeisnotineffect,andlessthanzeroiftheinformationisnotavailable.
[实行夏令时的时候,tm_isdst为正;不实行夏令时的时候,tm_isdst为0;不了解情况时,tm_isdst为负]
*tm_secisgenerally0-59.Theextrarangeistoaccommodateforleapsecondsincertainsystems.
[*tm_sec通常为0-59,多余的范围是为了在某些系统上适应闰秒]

注:夏令时是一种法定的时间。夏天太阳升起得比较早,白天时间很长,为了节约能源和充分利用白天宝贵的时间,世界上不少国家都采用法律规定的形式,每到夏天就将这个国家使用的时间提前一小时,也有提前半小时或几小时的;到了冬季,又将拨快的时间拨回来。这样的时间就是“夏令时”,是一种法定时间。

/*
time_ttime(time_t*timer);

Getcurrenttime
Getthecurrentcalendartimeasavalueoftypetime_t.
[该函数返回系统当前日历时间]
Thefunctionreturnsthisvalue,andiftheargumentisnotanullpointer,italsosetsthisvaluetotheobjectpointedbytimer.
[如果timer不是空指针,则用timer指向time_t类型的返回值]
Thevaluereturnedgenerallyrepresentsthenumberofsecondssince00:00hours,Jan1,1970UTC(i.e.,thecurrentunixtimestamp).Althoughlibrariesmayuseadifferentrepresentationoftime:Portableprogramsshouldnotusethevaluereturnedbythisfunctiondirectly,butalwaysrelyoncallstootherelementsofthestandardlibrarytotranslatethemtoportabletypes(suchaslocaltime,gmtimeordifftime).
[返回值通常表示的是自UTC时间1970年1月1日00:00:00至今经过的秒数(也就是当前的unix时间戳)。因为库也许会不同的方式表示时间,因此对于可移植程序来说,不应该直接使用该函数的返回值,而应该通过调用标准库中的其他元素来将其翻译为可移植类型(比如调用localtime,gmtime或者difftime)]
*/

#include<iostream>
#include<ctime>

intmain()
{
time_ttimer;
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");
return0;
}


/*
structtm*localtime(consttime_t*timer);

Converttime_ttotmaslocaltime
[将time_t转换为保存本地日历时间的结构体tm]
Usesthevaluepointedbytimertofillatmstructurewiththevaluesthatrepresentthecorrespondingtime,expressedforthelocaltimezone.
[利用指针timer指向的值填充结构体tm,使得tm中保存相对应的本地时区的日期时间]

/////////////////////////////////////////////////////////////////////


char*asctime(conststructtm*timeptr);

Converttmstructuretostring
[将tm结构体转换为字符串string]
InterpretsthecontentsofthetmstructurepointedbytimeptrasacalendartimeandconvertsittoaC-stringcontainingahuman-readableversionofthecorrespondingdateandtime.
[将指向tm结构体的timeptr的内容转换为相对应的字符串]
Thereturnedstringhasthefollowingformat:
[转换之后的字符串形式如下:]
WwwMmmddhh:mm:ssyyyy
WhereWwwistheweekday,Mmmthemonth(inletters),ddthedayofthemonth,hh:mm:ssthetime,andyyyytheyear.
[其中Www是星期几,Mmm是月,dd是日,hh:mm:ss是时间,yyyy是年]
Thestringisfollowedbyanew-linecharacter('\n')andterminatedwithanull-character.
[返回的字符串会自动添加一个null作为字符串结束符,还会自动添加一个换行符'\n']
Itisdefinedwithabehaviorequivalentto:
[该函数定义的行为等价于以下操作:]
char*asctime(conststructtm*timeptr)
{
staticconstcharwday_name[][4]={
"Sun","Mon","Tue","Wed","Thu","Fri","Sat"
};
staticconstcharmon_name[][4]={
"Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec"
};
staticcharresult[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);
returnresult;
}
Foranalternativewithcustomdateformatting,seestrftime.
[自定义日期格式,请参看strftime]
*/

intmain()
{
time_trawtime;
structtm*timeinfo;

time(&rawtime);
timeinfo=localtime(&rawtime);
std::cout<<"Currentlocaltimeanddateis:"<<asctime(timeinfo);

system("pause");
return0;
}


/*
char*ctime(consttime_t*timer);

Converttime_tvaluetostring
[将time_t值转换为字符串]
InterpretsthevaluepointedbytimerasacalendartimeandconvertsittoaC-stringcontainingahuman-readableversionofthecorrespondingtimeanddate,intermsoflocaltime.
[将指向time_t的timer的内容转换为相对应的字符串]
Thereturnedstringhasthefollowingformat:
[返回的字符串格式如下:]
WwwMmmddhh:mm:ssyyyy
WhereWwwistheweekday,Mmmthemonth(inletters),ddthedayofthemonth,hh:mm:ssthetime,andyyyytheyear.
[其中Www是星期几,Mmm是月,dd是日,hh:mm:ss是时间,yyyy是年]
Thestringisfollowedbyanew-linecharacter('\n')andterminatedwithanull-character.
[返回的字符串会自动添加一个null作为字符串结束符,还会自动添加一个换行符'\n']
Thisfunctionisequivalentto:
[该函数等价于:]
asctime(localtime(timer))
Foranalternativewithcustomdateformatting,seestrftime.
[自定义日期格式,请参看strftime]
*/

#include<iostream>
#include<ctime>

intmain()
{
time_trawtime;

time(&rawtime);
std::cout<<"Thecurrentlocaltimeis:"<<ctime(&rawtime);

system("pause");
return0;
}


/*
time_tmktime(structtm*timeptr);

Converttmstructuretotime_t
[将tm结构体转换为time_t]
Returnsthevalueoftypetime_tthatrepresentsthelocaltimedescribedbythetmstructurepointedbytimeptr(whichmaybemodified).
[将tm结构体代表的本地时间转换为time_t格式]
Thisfunctionperformsthereversetranslationthatlocaltimedoes.
[该函数的作用与localtime()函数的作用恰好相反]
Thevaluesofthememberstm_wdayandtm_ydayoftimeptrareignored,andthevaluesoftheothermembersareinterpretedevenifoutoftheirvalidranges(seestructtm).Forexample,tm_mdaymaycontainvaluesabove31,whichareinterpretedaccordinglyasthedaysthatfollowthelastdayoftheselectedmonth.
[tm结构体中的成员tm_wday和tm_yday会被忽略,其他成员即使其取值超出有效范围也会被进行解释,如果tm_mday可能大于31,但也会被相应地解释为这个月的最后一天]
Acalltothisfunctionautomaticallyadjuststhevaluesofthemembersoftimeptriftheyareoff-rangeor-inthecaseoftm_wdayandtm_yday-iftheyhavevaluesthatdonotmatchthedatedescribedbytheothermembers.
[该函数会自动调整tm结构体的值,即使其值超出范围,或者tm_wday及tm_yday与由其他成员所描述出来的日期不匹配]

ReturnValue
Atime_tvaluecorrespondingtothecalendartimepassedasargument.
[返回函数参数所对应的time_t值]
Ifthecalendartimecannotberepresented,avalueof-1isreturned.
[如果不能把信息表示为合法日历,则返回-1]
*/

#include<iostream>
#include<ctime>

intmain()
{
time_trawtime;
structtm*timeinfo;
intyear,month,day;
constchar*weekday[]={
"Sunday","Monday",
"Tuesday","Wednesday",
"Thursday","Friday","Saturday"
};

std::cout<<"Enteryear:";std::cin>>year;
std::cout<<"Entermonth:";std::cin>>month;
std::cout<<"Enterday:";std::cin>>day;

time(&rawtime);
timeinfo=localtime(&rawtime);
timeinfo->tm_year=year-1900;
timeinfo->tm_mon=month-1;
timeinfo->tm_mday=day;

/*callmktime:timeinfo->tm_wdaywillbeset*/
mktime(timeinfo);

std::cout<<"Thatdayisa"<<weekday[timeinfo->tm_wday]<<'\n';

system("pause");
return0;
}



/*
size_tstrftime(char*ptr,size_tmaxsize,constchar*format,conststructtm*timeptr);

Formattimeasstring
[将tm结构体格式化为字符串]
Copiesintoptrthecontentofformat,expandingitsformatspecifiersintothecorrespondingvaluesthatrepresentthetimedescribedintimeptr,withalimitofmaxsizecharacters.
[将tm结构体的参数按参数format所设定的格式进行格式化,并将格式化后的结果放到字符串ptr中(至多maxsize个字符)]

maxsize
Maximumnumberofcharacterstobecopiedtoptr,includingtheterminatingnull-character.
[拷贝到ptr中的最大字符数目,包括null结束符]

ReturnValue
IfthelengthoftheresultingCstring,includingtheterminatingnull-character,doesn'texceedmaxsize,thefunctionreturnsthetotalnumberofcharacterscopiedtoptr(notincludingtheterminatingnull-character).
Otherwise,itreturnszero,andthecontentsofthearraypointedbyptrareindeterminate.
[如果字符串ptr的长度(包括null结束符)没有超过maxsize,则该函数返回字符串ptr中字符的个数(不包括null结束符);否则返回0,且ptr的内容未定义]

format
用于设定格式的说明符如下:
specifierReplacedbyExample
%aAbbreviatedweekdayname*Thu
%AFullweekdayname*Thursday
%bAbbreviatedmonthname*Aug
%BFullmonthname*August
%cDateandtimerepresentation*ThuAug2314:55:022001
%CYeardividedby100andtruncatedtointeger(00-99)20
%dDayofthemonth,zero-padded(01-31)23
%DShortMM/DD/YYdate,equivalentto%m/%d/%y08/23/01
%eDayofthemonth,space-padded(1-31)23
%FShortYYYY-MM-DDdate,equivalentto%Y-%m-%d2001-08-23
%gWeek-basedyear,lasttwodigits(00-99)01
%GWeek-basedyear2001
%hAbbreviatedmonthname*(sameas%b)Aug
%HHourin24hformat(00-23)14
%IHourin12hformat(01-12)02
%jDayoftheyear(001-366)235
%mMonthasadecimalnumber(01-12)08
%MMinute(00-59)55
%nNew-linecharacter('\n')
%pAMorPMdesignationPM
%r12-hourclocktime*02:55:02pm
%R24-hourHH:MMtime,equivalentto%H:%M14:55
%SSecond(00-61)02
%tHorizontal-tabcharacter('\t')
%TISO8601timeformat(HH:MM:SS),equivalentto%H:%M:%S14:55:02
%uISO8601weekdayasnumberwithMondayas1(1-7)4
%UWeeknumberwiththefirstSundayasthefirstdayofweekone(00-53)33
%VISO8601weeknumber(00-53)34
%wWeekdayasadecimalnumberwithSundayas0(0-6)4
%WWeeknumberwiththefirstMondayasthefirstdayofweekone(00-53)34
%xDaterepresentation*08/23/01
%XTimerepresentation*14:55:02
%yYear,lasttwodigits(00-99)01
%YYear2001
%zISO8601offsetfromUTCintimezone(1minute=1,1hour=100)+100

Iftimezonecannotbetermined,nocharacters

%ZTimezonenameorabbreviation*CDT
Iftimezonecannotbetermined,nocharacters
%%A%sign%
*Thespecifiersmarkedwithanasterisk(*)arelocale-dependent.
*/

#include<iostream>
#include<ctime>

intmain()
{
time_ttimer;
structtm*timeinfo;
charbuffer[80];

time(&timer);
timeinfo=localtime(&timer);

strftime(buffer,80,"Nowit's%I:%M%p",timeinfo);
std::cout<<buffer<<'\n';

system("pause");
return0;
}



/*
structtm*gmtime(consttime_t*timer);

Converttime_ttotmasUTCtime
[将time_t转换为tm格式的UTC时间]
Usesthevaluepointedbytimertofillatmstructurewiththevaluesthatrepresentthecorrespondingtime,expressedasaUTCtime(i.e.,thetimeattheGMTtimezone).
[将指向time_t的指针timer的内容转换为对应的UTC时间]
Foralocaltimealternative,seelocaltime.
[如果想要转换成本地时间,请看localtime]
*/

#include<iostream>
#include<ctime>

#defineMST(-7)
#defineUTC(0)
#defineCCT(+8)

intmain()
{
time_trawtime;
structtm*ptm;

time(&rawtime);
ptm=gmtime(&rawtime);

std::cout<<"CurrenttimearoundtheWorld:\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");
return0;
}


/*
clock_tclock(void);

Clockprogram
Returnstheprocessortimeconsumedbytheprogram.
[返回自程序开始运行的处理器时间]
Thevaluereturnedisexpressedinclockticks,whichareunitsoftimeofaconstantbutsystem-specificlength(witharelationofCLOCKS_PER_SECclocktickspersecond).
[该函数的返回值使用时钟嘀嗒数来表示,时钟嘀嗒是时间的单位,它是一个常量,但其长度由系统决定(时钟嘀嗒数除以CLOCKS_PER_SEC即转换为秒数)]
Theepochusedasreferencebyclockvariesbetweensystems,butitisrelatedtotheprogramexecution(generallyitslaunch).Tocalculatetheactualprocessingtimeofaprogram,thevaluereturnedbyclockshallbecomparedtoavaluereturnedbyapreviouscalltothesamefunction.
[不同时代的系统时钟不一样,但时钟与程序运行时间相关,如果要计算程序运行的实际时间,应该计算两个时钟嘀嗒数的差值]
*/

#include<iostream>
#include<ctime>
#include<cmath>

intfrequency_of_primes(intn){//求1-n之间素数的个数
inti,j;
intfreq=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;}
returnfreq;
}

intmain()
{
clock_tt;
intf;
t=clock();
std::cout<<"Calculating...\n";
f=frequency_of_primes(99999);
std::cout<<"Thenumberofprimeslowerthan100,000is:"<<f<<'\n';
t=clock()-t;
std::cout<<"Ittookme"<<t<<"clicks("<<(float)t/CLOCKS_PER_SEC<<"seconds)"<<'\n';

system("pause");
return0;
}


/*
doubledifftime(time_tend,time_tbeginning);

Returndifferencebetweentwotimes
[返回时间差]
Calculatesthedifferenceinsecondsbetweenbeginningandend.
[计算beginning和end之间相差的秒数]
*/

#include<iostream>
#include<ctime>

intmain()
{
time_tnow;
structtmnewyear;
doubleseconds;

time(&now);

newyear=*localtime(&now);

newyear.tm_hour=newyear.tm_hour-1;

seconds=difftime(now,mktime(&newyear));

std::cout<<seconds<<"secondssincenewyearinthecurrenttimezone.\n";

system("pause");
return0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
章节导航