c言語フォーマット時間


#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
",now()); sleep(1); } return 0; }