시간을 형식으로 인쇄하는 방법 : 2009‐08‐10 18 : 17 : 54.811
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;
time(&timer);
tm_info = localtime(&timer);
strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
puts(buffer);
return 0;
}
밀리 초 부분에 대해서는이 질문을보십시오. ANSI C를 사용하여 시간을 밀리 초 단위로 측정하는 방법은 무엇입니까?
위의 답변은 질문 (특히 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;
}
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
If you're really constrained by the specs and do not want the space between the day and hour, just remove it from the format string.
Following code prints with microsecond precision. All we have to do is use gettimeofday
and strftime
on tv_sec
and append tv_usec
to the constructed string.
#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;
}
You could use strftime
, but struct tm
doesn't have resolution for parts of seconds. I'm not sure if that's absolutely required for your purposes.
struct tm tm;
/* Set tm to the correct time */
char s[20]; /* strlen("2009-08-10 18:17:54") + 1 */
strftime(s, 20, "%F %H:%M:%S", &tm);
참고URL : https://stackoverflow.com/questions/3673226/how-to-print-time-in-format-2009-08-10-181754-811
'IT박스' 카테고리의 다른 글
Maven 어셈블리 플러그인에서 생성 한 전쟁 이름을 어떻게 변경할 수 있습니까? (0) | 2020.09.23 |
---|---|
Msysgit bash는 Windows 7에서 끔찍하게 느립니다. (0) | 2020.09.22 |
루비 날짜 빼기 (예 : 90 일 전) (0) | 2020.09.22 |
인앱 구매를 테스트하려고 할 때 iTunes 계정 생성이 허용되지 않음 (0) | 2020.09.22 |
Python의 timeit으로 "글로벌 이름 'foo'가 정의되지 않았습니다."가져 오기 (0) | 2020.09.22 |