ITeye博客

c语言格式化时间

kingoal · 2009-05-19 22:03 · Others · Markdown

#include <time.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char* current_time()
{
	struct timeval now;
	static char str[30];
	char* ptr;

	if(gettimeofday(&now,NULL)<0)
	{
		perror("gettimeofday");
		exit(-1);
	}

	ptr = ctime(&now.tv_sec);
	strcpy(str,ptr+11);
	snprintf(str+8,sizeof(str)-8,".%06ld",now.tv_usec);

	return str;
}

const char* now()
{
	static char str[30];
	struct tm* pTm;

	time_t seconds = time(NULL);
	pTm = localtime(&seconds);

	sprintf(str,"%d-%d-%d %d:%d:%d",pTm->tm_year+1900,pTm->tm_mon+1,pTm->tm_mday,pTm->tm_hour,pTm->tm_min,pTm->tm_sec);

	return str;
}

int main(int argc,char* argv[])
{
	int i = 0;
	for(;i<10;i++)
	{
		printf("Current time: %s\n",now());
		sleep(1);
	}

	return 0;
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。