時間日期設置--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)          +100               
              If 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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM