C语言 ctime()

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C语言 ctime()相关的知识,希望对你有一定的参考价值。

这个函数在执行时做了什么?

没有 #include <ctime> 的写法,只有 #include <time.h>,time.h 是C语言里时间的库函数。
ctime在C语言里,只是一个把日期和时间转换为字符串的函数。具体函数原型为:
char *ctime( const time_t *timer )
用法实例:
#include <stdio.h>
#include <time.h>
int main( void )

time_t ltime;
time( <ime ); //获取当前的系统时间
printf( "The time is %s\n", ctime( <ime ) ); //把当前的系统时间转换成字符串格式输出来
return 0;


假如当前的系统时间是2011年1月19日,15时16分20秒,星期三,那么经过这段程序运行后,在显示终端上出现:The time is Wed Jan 19 15:16:20 2011
参考技术A asctime是把时间换成ascii码。
ctime是把时间转换成字符串。

具体介绍如下:

函数名: asctime
功 能: 转换日期和时间为ASCII码
用 法: char *asctime(const struct tm *tblock);
程序例:
#include <stdio.h>
#include <string.h>
#include <time.h>
int main(void)

struct tm t;
char str[80];
/* sample loading of tm structure */
t.tm_sec = 1; /* Seconds */
t.tm_min = 30; /* Minutes */
t.tm_hour = 9; /* Hour */
t.tm_mday = 22; /* Day of the Month */
t.tm_mon = 11; /* Month */
t.tm_year = 56; /* Year - does not include century */
t.tm_wday = 4; /* Day of the week */
t.tm_yday = 0; /* Does not show in asctime */
t.tm_isdst = 0; /* Is Daylight SavTime; does not show in asctime */
/* converts structure to null terminated
string */
strcpy(str, asctime(&t));
printf("%s\n", str);
return 0;

英文详解:
[编辑本段]asctime

Synopsis
#include <time.h>
char *asctime(const struct tm *timeptr);
Description
The asctime function converts the broken-down time in the structure pointed to by timeptr into a string in the form
Sun Sep 16 01:03:52 1973\n\0
using the equivalent of the following algorithm.
char *asctime(const struct tm *timeptr)

static const char wday_name[7][3] =
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
;
static const char mon_name[12][3] =
"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;

Returns
The asctime function returns a pointer to the string.
Example :
#include <stdio.h>
#include <time.h>
void main(void)

struct tm *newtime;
time_t ltime;
/* Get the time in seconds */
time (<ime);
/* convert it to the structure tm */
newtime = localtime(<ime);
/* print the local time as a string */
printf("The current time and dat are %s", asctime(newtime));

The current time and dat are Mon Dec 28 12:33:50 1998

ctime
函数名: ctime
功 能: 把日期和时间转换为字符串
用 法: char *ctime(const time_t *time);
程序例:
#include
#include
int main(void)

time_t t;
time(&t);
printf("Today's date and time: %s\n", ctime(&t));
return 0;

求采纳为满意回答。
参考技术B 就是显示当前的时间。 怎么显示忘了 好像能赋值给一个变量把,

以上是关于C语言 ctime()的主要内容,如果未能解决你的问题,请参考以下文章

c语言中时间处理

C语言如何返回格式化日期时间?(将日期和时间以字符串格式输出)ctime()asctime()localtime()

VC++中的CTime头文件是啥?

C++中CTime的头文件

#include <ctime>在c 中是啥意思

C语言如何获取文件创建时间?