跳轉到內容

C++ 程式設計/程式碼/標準 C 庫/時間和日期

來自 Wikibooks,開放世界中的開放書籍

標準 C 時間和日期

[編輯 | 編輯原始碼]

本節將涵蓋 C 標準庫中時間和日期元素。

語法
#include <ctime>
char *asctime( const struct tm *ptr );

asctime() 函式將 struct 'ptr' 中的時間轉換為以下格式的字元字串

day month date hours:minutes:seconds year

示例

Mon Jun 26 12:03:53 2000
相關主題
clock - ctime - difftime - gmtime - localtime - mktime - time
語法
#include <ctime>
clock_t clock( void );

clock() 函式返回程式啟動以來的處理器時間,如果該資訊不可用,則返回 -1。要將返回值轉換為秒,請將其除以 CLOCKS_PER_SEC

注意
如果您的編譯器和庫符合 POSIX 標準,則 CLOCKS_PER_SEC 始終定義為 1000000。

相關主題
asctime - ctime - time
語法
#include <ctime>
char *ctime( const time_t *time );

ctime() 函式將日曆時間 time 轉換為以下格式的本地時間

day month date hours:minutes:seconds year            

使用 ctime() 等同於

asctime( localtime( tp ) );
相關主題
asctime - clock - gmtime - localtime - mktime - time
語法
#include <ctime>
double difftime( time_t time2, time_t time1 );

difftime() 函式以秒為單位返回 time2 - time1

相關主題
asctime - gmtime - localtime - time
語法
#include <ctime>
struct tm *gmtime( const time_t *time );

gmtime() 函式以協調世界時 (通常為格林尼治標準時間) 返回給定的時間,除非系統不支援,在這種情況下返回 NULL。注意 靜態返回

相關主題
asctime - ctime - difftime - localtime - mktime - strftime - time

localtime

[編輯 | 編輯原始碼]
語法
#include <ctime>
struct tm *localtime( const time_t *time );

localtime() 函式將日曆時間 time 轉換為本地時間。注意 靜態返回

相關主題
asctime - ctime - difftime - gmtime - strftime - time
語法
#include <ctime>
time_t mktime( struct tm *time );

mktime() 函式將 time 中的本地時間轉換為日曆時間,並返回它。如果發生錯誤,則返回 -1。

相關主題
asctime - ctime - gmtime - time

setlocale

[編輯 | 編輯原始碼]
語法
#include <clocale>
char *setlocale( int category, const char * locale );

setlocale() 函式用於設定和檢索當前區域設定。如果 localeNULL,則返回當前區域設定。否則,locale 用於為給定的 category 設定區域設定。

category 可以具有以下值

描述
LC_ALL 所有區域設定
LC_TIME 日期和時間格式
LC_NUMERIC 數字格式
LC_COLLATE 字串排序和正則表示式匹配
LC_CTYPE 正則表示式匹配、轉換、區分大小寫的比較、寬字元函式和字元分類。
LC_MONETARY 用於貨幣格式
LC_MESSAGES 用於自然語言訊息
相關主題
(標準 C 字串和字元) strcoll
語法
#include <ctime>
size_t strftime( char *str, size_t maxsize, const char *fmt, struct tm *time );

strftime() 函式根據 fmt 指定的格式,將 time 中的日期和時間資訊格式化為字串,然後將結果儲存在 str 中(最多 maxsize 個字元)。可以在 fmt 中使用某些程式碼來指定不同型別的 time

程式碼 含義
%a 縮寫星期名稱 (例如 Fri)
%A 完整星期名稱 (例如 Friday)
%b 縮寫月份名稱 (例如 Oct)
%B 完整月份名稱 (例如 October)
%c 標準日期和時間字串
%d 月份中的日期,作為帶前導零的數字 (01-31)
%-d 月份中的日期,作為不帶前導零的數字 (1-31)
%H 小時,24 小時制 (0-23)
%I 小時,12 小時制 (1-12)
%j 一年中的日期,作為數字 (1-366)
%m 月份作為數字 (1-12)。
%M 分鐘作為數字 (0-59)
%p 區域設定的 AM 或 PM 等效項
%S 秒作為數字 (0-59)
%U 一年中的星期,(0-53),其中第一週的第一天是星期日
%w 星期幾作為十進位制數 (0-6),其中星期日為 0
%W 一年中的星期,(0-53),其中第一週的第一天是星期一
%x 標準日期字串
%X 標準時間字串
%y 年份以十進位制表示,不帶世紀 (0-99)
%Y 年份以十進位制表示,帶世紀
%Z 時區名稱
%% 百分號

注意
某些版本的 Microsoft Visual C++ 可能使用 0-11 之間的數值來描述 %m(月份的數字表示)。

相關主題
gmtime - localtime - time
語法
#include <ctime>
time_t time( time_t *time );

time() 函式返回當前時間,如果出現錯誤則返回 -1。如果給定了 time 引數,則當前時間將儲存在 time 中。

相關主題
asctime - clock - ctime - difftime - gmtime - localtime - mktime - strftime
(其他標準 C 函式)srand - 預處理宏 __DATE__ 和 __TIME__
華夏公益教科書