C 프로그램에서 날짜와 시간 값을 얻는 방법은 무엇입니까?
이런 게 있어요.
char *current_day, *current_time;
system("date +%F");
system("date +%T");
시간을 만, 이 stdout에 하고 싶습니다.current_day
★★★★★★★★★★★★★★★★★」current_time
나중에 해당 값으로 처리할 수 있도록 변수를 지정합니다.
current_day ==> current day
current_time ==> current time
할 수 있는 유도하고 및 을 에 입니다.current_day
★★★★★★★★★★★★★★★★★」current_time
지지 、 이은은은좋좋 것아아것 。아, 른른?
및 를 사용하여 시간을 가져옵니다.
#include <stdio.h>
#include <time.h>
int main()
{
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf("now: %d-%02d-%02d %02d:%02d:%02d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
}
strftime
(C89)
Martin이 언급했습니다. 예를 들어 보겠습니다.
메인
#include <assert.h>
#include <stdio.h>
#include <time.h>
int main(void) {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
char s[64];
assert(strftime(s, sizeof(s), "%c", tm));
printf("%s\n", s);
return 0;
}
GitHub 업스트림
컴파일 및 실행:
gcc -std=c89 -Wall -Wextra -pedantic -o main.out main.c
./main.out
샘플 출력:
Thu Apr 14 22:39:03 2016
%c
는 정음음음음음음음음 as as as as as as as as as as as as as와 같은 을 생성합니다.ctime
.
이 함수의 장점 중 하나는 쓴 바이트 수를 반환하여 생성된 문자열이 너무 길 경우 오류 제어를 개선할 수 있다는 것입니다.
반환값
결과 문자열(종료 눌바이트 포함)이 최대 바이트를 초과하지 않는 경우 strftime()은 배열에 배치된 바이트 수(종료 눌바이트 제외)를 반환합니다.결과 문자열의 길이(종료하는 늘바이트 포함)가 최대 바이트를 초과할 경우 strftime()은 0을 반환하고 배열 내용은 정의되지 않습니다.
반환값 0이 반드시 오류를 나타내는 것은 아닙니다.예를 들어 많은 로케일에서 %p는 빈 문자열을 생성합니다.빈 형식 문자열도 마찬가지로 빈 문자열이 생성됩니다.
asctime
★★★★★★★★★★★★★★★★★」ctime
7에서 되지 않음C89, POSIX 7에서 권장되지 않음)
asctime
한 형식입니다.struct tm
:
메인
#include <stdio.h>
#include <time.h>
int main(void) {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
printf("%s", asctime(tm));
return 0;
}
샘플 출력:
Wed Jun 10 16:10:32 2015
and고.........ctime()
표준에는 다음과 같은 지름길이 명시되어 있습니다.
asctime(localtime())
Jonathan Leffler가 말했듯이 이 포맷에는 시간대 정보가 없다는 단점이 있습니다.
POSIX 7은 이러한 기능을 "청소년"으로 표시하여 향후 버전에서 제거할 수 있도록 했습니다.
asctime()이 ISO C 표준에 포함되어 있어도 버퍼 오버플로우 가능성이 있기 때문에 표준 개발자는 asctime() 및 asctime_r() 함수를 objective로 표시하기로 결정했습니다.ISO C 표준은 이러한 문제를 피하기 위해 사용할 수 있는 strftime() 함수를 제공합니다.
이 질문의 C++ 버전:현재 날짜와 시간을 C++로 얻는 방법
Ubuntu 16.04로 테스트.
time_t rawtime;
time ( &rawtime );
struct tm *timeinfo = localtime ( &rawtime );
를 사용하여 시간을 문자열로 포맷할 수도 있습니다.
WinAPI를 사용하여 날짜와 시간을 얻을 수 있습니다.이 방법은 Windows에만 한정됩니다만, Windows만을 대상으로 하고 있거나 WinAPI를 이미 사용하고 있는 경우는, 다음의 가능성이 있습니다1.
를 사용하면 시간과 날짜를 모두 얻을 수 있습니다. struct
중 둘 중 하나)를GetLocalTime()
★★★★★★★★★★★★★★★★★」GetSystemTime()
)를 사용하여 구조물을 채웁니다.
GetLocalTime()
는 사용자의 시간대에 고유한 시간과 날짜를 제공합니다.
GetSystemTime()
는 시간과 날짜를 UTC로 제공합니다.
그 struct
에는 다음 멤버가 있습니다.
wYear
,wMonth
,wDayOfWeek
,wDay
,wHour
,wMinute
,wSecond
★★★★★★★★★★★★★★★★★」wMilliseconds
그런 다음 구조물에 정기적으로 접근하면 됩니다.
실제 코드 예시:
#include <windows.h> // use to define SYSTEMTIME , GetLocalTime() and GetSystemTime()
#include <stdio.h> // For printf() (could otherwise use WinAPI equivalent)
int main(void) { // Or any other WinAPI entry point (e.g. WinMain/wmain)
SYSTEMTIME t; // Declare SYSTEMTIME struct
GetLocalTime(&t); // Fill out the struct so that it can be used
// Use GetSystemTime(&t) to get UTC time
printf("Year: %d, Month: %d, Day: %d, Hour: %d, Minute:%d, Second: %d, Millisecond: %d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds); // Return year, month, day, hour, minute, second and millisecond in that order
return 0;
}
(간단하고 알기 쉽게 코드화되어 있습니다.더 나은 포맷 방법에 대해서는 원래의 답변을 참조해 주세요.)
출력은 다음과 같습니다.
Year: 2018, Month: 11, Day: 24, Hour: 12, Minute:28, Second: 1, Millisecond: 572
유용한 참고 자료:
모든 WinAPI 문서(대부분 이미 위에 열거되어 있음):
Zetcode에 의한 이 주제에 대한 매우 훌륭한 초보자용 튜토리얼:
Codeproject에서 datetime을 사용한 간단한 작업:
Ori ('1: Ori Osherov')에 기재되어 있는 와 같이Given that OP started with date +%F, they're almost certainly not using Windows. – melpomene Sep 9 at 22:17
OP는 Windows를 사용하지 않습니다만, 이 질문에는 플랫폼 고유의 태그가 붙어 있지 않습니다(또한 특정 시스템에 대한 답변이 있어야 한다는 것도 기재되어 있지 않습니다).또, 구글링의 「c」의 경우, 그 양쪽의 답변이 모두 여기에 포함되는 경우는, 이 질문에 대한 답변을 찾는 유저도 Windows에 있는 경우가 있기 때문에, 이 질문에 대한 답변은 Windows에 있는 경우가 있습니다.e는 그들에게 유용하다.
파일 대신 파이프를 사용하고 C++가 아닌 C를 사용하는 경우 이렇게 팝펜을 사용할 수 있습니다.
#include<stdlib.h>
#include<stdio.h>
FILE *fp= popen("date +F","r");
fgets와 함께 *fp를 일반 파일 포인터로 사용합니다.
u wana 가 c++ 문자열을 사용하는 경우는, 아이를 포크 해 커맨드를 기동해, 그것을 부모에게 파이프 합니다.
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;
string currentday;
int dependPipe[2];
pipe(dependPipe);// make the pipe
if(fork()){//parent
dup2(dependPipe[0],0);//convert parent's std input to pipe's output
close(dependPipe[1]);
getline(cin,currentday);
} else {//child
dup2(dependPipe[1],1);//convert child's std output to pipe's input
close(dependPipe[0]);
system("date +%F");
}
// 날짜 + T에 대해서도 같은 1을 만들 수 있지만, 시간 내에 작업을 수행할 것을 권장합니다.h GL
Timespec에는 요일이 포함되어 있습니다.
http://pubs.opengroup.org/onlinepubs/7908799/xsh/time.h.html
#include <time.h>
int get_day_of_year(){
time_t t = time(NULL);
struct tm tm = *localtime(&t);
return tm.tm_yday;
}`
위의 답변은 적절한 CRT 답변이지만, 필요한 경우 Win32 솔루션을 사용할 수도 있습니다.거의 동일하지만 IMO를 Windows용으로 프로그래밍하는 경우에는 API를 사용하는 것이 좋습니다(Windows에서 프로그래밍하는지는 모르겠지만).
char* arrDayNames[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
SYSTEMTIME st;
GetLocalTime(&st); // Alternatively use GetSystemTime for the UTC version of the time
printf("The current date and time are: %d/%d/%d %d:%d:%d:%d", st.wDay, st.wMonth, st.wYear, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
printf("The day is: %s", arrDayNames[st.wDayOfWeek]);
어쨌든 이것은 Windows 솔루션입니다.언젠가 너에게 도움이 되었으면 좋겠어!
#include<stdio.h>
using namespace std;
int main()
{
printf("%s",__DATE__);
printf("%s",__TIME__);
return 0;
}
명령어 라인 C 컴파일러를 사용하여 컴파일을 하고 있었는데 컴파일이 거부되어 완전히 정신이 나갔습니다.
어떤 이유에서인지 컴파일러는 제가 함수를 선언하고 사용하는 것을 싫어했습니다.
struct tm tm = *localtime(&t);
test.c
test.c(494) : error C2143: syntax error : missing ';' before 'type'
Compiler Status: 512
먼저 변수를 선언하고 함수를 호출합니다.이렇게 했어요.
char todayDateStr[100];
time_t rawtime;
struct tm *timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
strftime(todayDateStr, strlen("DD-MMM-YYYY HH:MM")+1,"%d-%b-%Y %H:%M",timeinfo);
printf("todayDateStr = %s ... \n", todayDateStr );
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct date
{
int month;
int day;
int year;
};
int calcN(struct date d)
{
int N;
int f(struct date d);
int g(int m);
N = 1461 * f(d) / 4 + 153 * g(d.month) / 5 + d.day;
if(d.year < 1700 || (d.year == 1700 && d.month < 3))
{
printf("Date must be after February 29th, 1700\n");
return 0;
}
else if(d.year < 1800 || (d.year == 1800 && d.month < 3))
N += 2;
else if(d.year < 1900 || (d.year == 1900 && d.month < 3))
N += 1;
return N;
}
int f(struct date d)
{
if(d.month <= 2)
d.year -= 1;
return d.year;
}
int g(int m)
{
if(m <=2)
m += 13;
else
m += 1;
return m;
}
int main(void)
{
int calcN(struct date d);
struct date d1, d2;
int N1, N2;
time_t t;
time(&t);
struct tm *now = localtime(&t);
d1.month = now->tm_mon + 1;
d1.day = now->tm_mday;
d1.year = now->tm_year + 1900;
printf("Today's date: %02i/%02i/%i\n", d1.month, d1.day, d1.year);
N1 = calcN(d1);
printf("Enter birthday (mm dd yyyy): ");
scanf("%i%i%i", &d2.month, &d2.day, &d2.year);
N2 = calcN(d2);
if(N2 == 0)
return 0;
printf("Number of days since birthday: %i\n", N1 - N2);
return 0;
}
현지 시간 정보를 얻기 위한 라이너 1개:struct tm *tinfo = localtime(&(time_t){time(NULL)});
언급URL : https://stackoverflow.com/questions/1442116/how-to-get-the-date-and-time-values-in-a-c-program
'IT이야기' 카테고리의 다른 글
2개의 Java 8 스트림 또는 스트림에 추가 요소 추가 (0) | 2022.05.27 |
---|---|
Java에서 클래스 변수를 덮어쓰는 방법이 있나요? (0) | 2022.05.27 |
IntelliJ IDEA가 인터페이스에서 Java 구현 클래스로의 도약 (0) | 2022.05.27 |
__DA 사용방법TE__와 __TIME__의 매크로가 2개의 정수로 정의되어 있습니다.그러면 스트링화? (0) | 2022.05.27 |
Maven: 상대 경로로 항아리에 종속성을 추가합니다. (0) | 2022.05.27 |