C 형식으로 시간을 인쇄하는 가장 좋은 방법은 무엇입니까 2009‐08‐10
18:17:54.811?
답변:
strftime () 사용하십시오 .
#include <stdio.h>
#include <time.h>
int main()
{
time_t timer;
char buffer[26];
struct tm* tm_info;
timer = time(NULL);
tm_info = localtime(&timer);
strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
puts(buffer);
return 0;
}
밀리 초 부분에 대해서는이 질문을보십시오. ANSI C를 사용하여 시간을 밀리 초 단위로 측정하는 방법은 무엇입니까?
time(&timer)은이어야합니다 timer = time(NULL);. The tloc argument is obsolescent and should always be NULL in new code. When tloc is NULL, the call cannot fail.
위의 답변은 질문 (특히 millisec 부분)에 완전히 대답하지 않습니다. 이에 대한 내 해결책은 strftime 전에 gettimeofday를 사용하는 것입니다. 밀리 초를 "1000"으로 반올림하지 않도록주의하십시오. 이것은 Hamid Nazari의 답변을 기반으로합니다.
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <math.h>
int main() {
char buffer[26];
int millisec;
struct tm* tm_info;
struct timeval tv;
gettimeofday(&tv, NULL);
millisec = lrint(tv.tv_usec/1000.0); // Round to nearest millisec
if (millisec>=1000) { // Allow for rounding up to nearest second
millisec -=1000;
tv.tv_sec++;
}
tm_info = localtime(&tv.tv_sec);
strftime(buffer, 26, "%Y:%m:%d %H:%M:%S", tm_info);
printf("%s.%03d\n", buffer, millisec);
return 0;
}
gettimeofdayWindows 구현에서는 사용할 수 없습니다.
time.h다음과 같은 것을 사용하여 strftime텍스트 표현을 제공 할 수 있는 함수를 정의합니다 time_t.
#include <stdio.h>
#include <time.h>
int main (void) {
char buff[100];
time_t now = time (0);
strftime (buff, 100, "%Y-%m-%d %H:%M:%S.000", localtime (&now));
printf ("%s\n", buff);
return 0;
}
하지만 .NET Framework에서 사용할 수 없기 때문에 1 초 미만의 해상도를 제공하지 않습니다 time_t. 다음을 출력합니다.
2010-09-09 10:08:34.000
사양의 제약을 받고 있고 요일과 시간 사이의 공백을 원하지 않는 경우 형식 문자열에서 제거하면됩니다.
다음 코드는 마이크로 초 정밀도로 인쇄됩니다. 우리가 할 일은 사용하는 것입니다 gettimeofday및 strftime에 tv_sec와 APPEND tv_usec구성된 문자열.
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
int main(void) {
struct timeval tmnow;
struct tm *tm;
char buf[30], usec_buf[6];
gettimeofday(&tmnow, NULL);
tm = localtime(&tmnow.tv_sec);
strftime(buf,30,"%Y:%m:%dT%H:%M:%S", tm);
strcat(buf,".");
sprintf(usec_buf,"%dZ",(int)tmnow.tv_usec);
strcat(buf,usec_buf);
printf("%s",buf);
return 0;
}
장난:
int time_len = 0, n;
struct tm *tm_info;
struct timeval tv;
gettimeofday(&tv, NULL);
tm_info = localtime(&tv.tv_sec);
time_len+=strftime(log_buff, sizeof log_buff, "%y%m%d %H:%M:%S", tm_info);
time_len+=snprintf(log_buff+time_len,sizeof log_buff-time_len,".%03ld ",tv.tv_usec/1000);
이 페이지의 솔루션 중 어느 것도 저에게 효과가 없었고, 혼합하여 Windows 및 Visual Studio 2019에서 작동하도록 만들었습니다. 방법은 다음과 같습니다.
#include <Windows.h>
#include <time.h>
#include <chrono>
static int gettimeofday(struct timeval* tp, struct timezone* tzp) {
namespace sc = std::chrono;
sc::system_clock::duration d = sc::system_clock::now().time_since_epoch();
sc::seconds s = sc::duration_cast<sc::seconds>(d);
tp->tv_sec = s.count();
tp->tv_usec = sc::duration_cast<sc::microseconds>(d - s).count();
return 0;
}
static char* getFormattedTime() {
static char buffer[26];
// For Miliseconds
int millisec;
struct tm* tm_info;
struct timeval tv;
// For Time
time_t rawtime;
struct tm* timeinfo;
gettimeofday(&tv, NULL);
millisec = lrint(tv.tv_usec / 1000.0);
if (millisec >= 1000)
{
millisec -= 1000;
tv.tv_sec++;
}
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, 26, "%Y:%m:%d %H:%M:%S", timeinfo);
sprintf_s(buffer, 26, "%s.%03d", buffer, millisec);
return buffer;
}
결과 :
2020 : 08 : 02 06 : 41 : 59.107
2020 : 08 : 02 06 : 41 : 59.196