struct tm,time,localtime,mktime,ctime,gmtime,difftime,asctime,strftime

本文详细介绍了C++中常用的时间处理函数,包括获取当前时间、时间格式转换、时间戳到字符串转换等,并通过实例展示了如何使用这些函数进行日期与时间的计算。

1. struct tm

int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
MemberMeaningRange
tm_secseconds after the minute0-61*
tm_minminutes after the hour0-59
tm_hourhours since midnight0-23
tm_mdayday of the month1-31
tm_monmonths since January0-11
tm_yearyears since 1900
tm_wdaydays since Sunday0-6
tm_ydaydays since January 10-365
tm_isdstDaylight Saving Time flag

2. time      

Get current time
time_t time ( time_t * timer );

Example

/ *time example* /
#include <iostream>
#include <ctime>
using namespace std;


int main()
{
time_t seconds;
time(&seconds);
//或者seconds = time(NULL);
cout << seconds / 3600 << " hours since January 1,1970" << endl;

return 0;
}

Possible output:


3. localtime

<ctime>
struct tm * localtime ( const time_t * timer );
Convert time_t to tm as local time

Example

/*localtime example*/
#include <iostream>
#include <ctime>
using namespace std;


int main()
{
	time_t rawtime;
	struct tm* timeinfo;
	time(&rawtime);
	timeinfo = localtime(&rawtime);
	cout << "current local time and date: " << asctime(timeinfo);
	return 0;
}

Output:

4. mktime

time_t mktime ( struct tm * timeptr );
Convert tm structure to time_t

Example

/* mktime example: weekday calculator */
#include <iostream>
#include <ctime>
using namespace std;

int main()
{
	time_t rawtime;
	struct tm* timeinfo;
	int year,month,day;
	char* weekday[] = {
		"Sunday", 
		"Monday",
		"Tuesday", 
		"Wednesday",
		"Thursday",
		"Friday", 
		"Saturday"
	};
	
	cout << "Enter year: "; cin >> year;
	cout << "Enter month: "; cin >> month;
	cout << "Enter day: "; cin >> day;
	//将当前时间赋给rawtime
	time(&rawtime);
	//将rawtime转化为本地时间赋给timeinfo
	timeinfo = localtime(&rawtime);
	timeinfo->tm_year = year - 1900;
	timeinfo->tm_mon = month - 1;
	timeinfo->tm_mday = day;

	mktime(timeinfo);
	cout << "That day is a " << weekday[timeinfo->tm_wday] << endl;

	return 0;
}

Output:

5.ctime

<ctime>
char * ctime ( const time_t * timer );
Convert time_t value to string

Example

/*ctime example*/
#include <iostream>
#include <ctime>
using namespace std;

int main()
{
	time_t rawtime;
	time(&rawtime);
	cout << "Current local time is: " << ctime(&rawtime);

	return 0;
}

Output:

6. gmtime

<ctime>
struct tm * gmtime ( const time_t * timer );
Convert time_t to tm as UTC time

Example

/*gmtime example*/
#include <iostream>
#include <ctime>
using namespace std;

#define MST (-7)
#define UTC (0)
#define CCT (+8)

int main()
{
	time_t rawtime;
	struct tm * ptm;
	//将当前时间赋给rawtime
	time(&rawtime);cout << "time: " << rawtime << endl;
	//Convert time_t to tm
	ptm = gmtime(&rawtime);
	cout << "Current time around the World: ";
	cout << "Phoenix, AZ (U.S.): " << (ptm->tm_hour + MST) % 24
		<< ":" << ptm->tm_min << endl;
	cout << "Reykjavik (Iceland): " << (ptm->tm_hour + UTC) % 24
		<< ":" << ptm->tm_min << endl;
	cout << "Beijing (China): " << (ptm->tm_hour + CCT) % 24
		<< ":" << ptm->tm_min << endl;
	return 0;
}

Output:


7. difftime

<ctime>
double difftime ( time_t time2, time_t time1 );
Return difference between two times

Example

/*diifftime example*/
#include <iostream>
#include <ctime>
#include <string>
using namespace std;

int main()
{
	time_t start,end;
	string str;
	double dif;

	time(&start);
	cout << "Please input your name: ";
	cin >> str;
	time(&end);
	dif = difftime(end,start);
	cout << "Hi, " << str << "! It took you " << dif 
		<< "seconds to type your name. " << endl;

	return 0;
}

Output:

8. asctime

<ctime>
char * asctime ( const struct tm * timeptr );
Convert tm structure to string

Example

/* asctime example */
#include <iostream>
#include <ctime>
using namespace std;

int main()
{
	time_t rawtime;
	struct tm * timeinfo;
	time(&rawtime);
	timeinfo = localtime(&rawtime);
	cout << "Current date/time is: " << asctime(timeinfo);
	return 0;
}

Output:


9. strftime

<ctime>
size_t strftime ( char * ptr, size_t maxsize, const char * format,
                  const struct tm * timeptr );
Format time as string
specifierReplaced byExample
%aAbbreviated weekday name *Thu
%AFull weekday name *Thursday
%bAbbreviated month name *Aug
%BFull month name *August
%cDate and time representation *Thu Aug 23 14:55:02 2001
%dDay of the month (01-31)23
%HHour in 24h format (00-23)14
%IHour in 12h format (01-12)02
%jDay of the year (001-366)235
%mMonth as a decimal number (01-12)08
%MMinute (00-59)55
%pAM or PM designationPM
%SSecond (00-61)02
%UWeek number with the first Sunday as the first day of week one (00-53)33
%wWeekday as a decimal number with Sunday as 0 (0-6)4
%WWeek number with the first Monday as the first day of week one (00-53)34
%xDate representation *08/23/01
%XTime representation *14:55:02
%yYear, last two digits (00-99)01
%YYear2001
%ZTimezone name or abbreviationCDT
%%% sign%

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* strftime example */
#include <stdio.h>
#include <time.h>

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;
  char buffer [80];

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

  strftime (buffer,80,"Now it's %I:%M%p.",timeinfo);
  puts (buffer);
  
  return 0;
}

Example output:

Now it's 03:21PM.

#ifndef _TIME_H #define _TIME_H #ifdef __cplusplus extern "C" { #endif #include <features.h> #ifdef __cplusplus #define NULL 0L #else #define NULL ((void*)0) #endif #define __NEED_size_t #define __NEED_time_t #define __NEED_clock_t #define __NEED_struct_timespec #if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ || defined(_BSD_SOURCE) #define __NEED_clockid_t #define __NEED_timer_t #define __NEED_pid_t #define __NEED_locale_t #endif #include <bits/alltypes.h> #if defined(_BSD_SOURCE) || defined(_GNU_SOURCE) #define __tm_gmtoff tm_gmtoff #define __tm_zone tm_zone #endif struct tm { int tm_sec; int tm_min; int tm_hour; int tm_mday; int tm_mon; int tm_year; int tm_wday; int tm_yday; int tm_isdst; long __tm_gmtoff; const char *__tm_zone; }; clock_t clock (void); time_t time (time_t *); double difftime (time_t, time_t); time_t mktime (struct tm *); size_t strftime (char *__restrict, size_t, const char *__restrict, const struct tm *__restrict); struct tm *gmtime (const time_t *); struct tm *localtime (const time_t *); char *asctime (const struct tm *); char *ctime (const time_t *); int timespec_get(struct timespec *, int); #define CLOCKS_PER_SEC 1000000L #define TIME_UTC 1 #if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ || defined(_BSD_SOURCE) size_t strftime_l (char * __restrict, size_t, const char * __restrict, const struct tm * __restrict, locale_t); struct tm *gmtime_r (const time_t *__restrict, struct tm *__restrict); struct tm *localtime_r (const time_t *__restrict, struct tm *__restrict); char *asctime_r (const struct tm *__restrict, char *__restrict); char *ctime_r (const time_t *, char *); void tzset (void); struct itimerspec { struct timespec it_interval; struct timespec it_value; }; #define CLOCK_REALTIME 0 #define CLOCK_MONOTONIC 1 #define CLOCK_PROCESS_CPUTIME_ID 2 #define CLOCK_THREAD_CPUTIME_ID 3 #define CLOCK_MONOTONIC_RAW 4 #define CLOCK_REALTIME_COARSE 5 #define CLOCK_MONOTONIC_COARSE 6 #define CLOCK_BOOTTIME 7 #define CLOCK_REALTIME_ALARM 8 #define CLOCK_BOOTTIME_ALARM 9 #define CLOCK_SGI_CYCLE 10 #define CLOCK_TAI 11 #define TIMER_ABSTIME 1 int nanosleep (const struct timespec *, struct timespec *); int clock_getres (clockid_t, struct timespec *); int clock_gettime (clockid_t, struct timespec *); int clock_settime (clockid_t, const struct timespec *); int clock_nanosleep (clockid_t, int, const struct timespec *, struct timespec *); int clock_getcpuclockid (pid_t, clockid_t *); struct sigevent; int timer_create (clockid_t, struct sigevent *__restrict, timer_t *__restrict); int timer_delete (timer_t); int timer_settime (timer_t, int, const struct itimerspec *__restrict, struct itimerspec *__restrict); int timer_gettime (timer_t, struct itimerspec *); int timer_getoverrun (timer_t); extern char *tzname[2]; #endif #if defined(_XOPEN_SOURCE) || defined(_BSD_SOURCE) || defined(_GNU_SOURCE) char *strptime (const char *__restrict, const char *__restrict, struct tm *__restrict); extern int daylight; extern long timezone; extern int getdate_err; struct tm *getdate (const char *); #endif #if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) int stime(const time_t *); time_t timegm(struct tm *); #endif #ifdef __cplusplus } #endif #endif 以上是我的交叉工具链中的time.h定义,所以time_t到底在哪里定义的
最新发布
11-20
`time`、`gmtime`、`ctime` 和 `asctime` 是 Python 中用于处理时间和日期的内置函数,主要位于 `time` 模块中。以下是这些函数的详细说明和用法示例: 1. **`time.time()`** - **功能**:返回当前时间的时间戳(从 1970 年 1 月 1 日 00:00:00 UTC 到现在的秒数,浮点数)。 - **示例**: ```python import time current_timestamp = time.time() print(current_timestamp) # 输出类似 1630000000.123456 ``` 2. **`time.gmtime([secs])`** - **功能**:将时间戳(默认为当前时间)转换为 UTC 时区的 `struct_time` 对象(包含年、月、日、时、分、秒等信息)。 - **示例**: ```python import time utc_time = time.gmtime() # 当前时间的 UTC 时间 print(utc_time) # 输出类似 time.struct_time(tm_year=2023, tm_mon=8, tm_mday=1, ...) ``` 3. **`time.ctime([secs])`** - **功能**:将时间戳(默认为当前时间)转换为可读的字符串格式(本地时区)。 - **示例**: ```python import time readable_time = time.ctime() print(readable_time) # 输出类似 "Tue Aug 1 12:34:56 2023" ``` 4. **`time.asctime([t])`** - **功能**:将 `struct_time` 对象(如 `gmtime` 的返回值)转换为可读的字符串格式。 - **示例**: ```python import time utc_time = time.gmtime() formatted_time = time.asctime(utc_time) print(formatted_time) # 输出类似 "Tue Aug 1 04:34:56 2023"(UTC 时间) ``` ### 完整示例代码 ```python import time # 获取当前时间戳 timestamp = time.time() print("当前时间戳:", timestamp) # 转换为 UTC 的 struct_time utc_time = time.gmtime(timestamp) print("UTC 时间:", utc_time) # 转换为本地时区的可读字符串 local_time_str = time.ctime(timestamp) print("本地时间字符串:", local_time_str) # 将 struct_time 转换为字符串 formatted_utc = time.asctime(utc_time) print("UTC 时间字符串:", formatted_utc) ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值