Limetime's TimeLine
article thumbnail
Published 2022. 4. 16. 22:42
[C++] 현재 날짜와 시간 구하기. C&C++
반응형
 

C++에서는 현재 날짜랑 시간을 구하려면 어떻게 하나요?

플랫폼이랑 상관없이 현재 시간, 날짜를 알고 싶습니다. 도와주세요

hashcode.co.kr

#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>

using namespace std;

int main() {
	time_t     now = time(0); //현재 시간을 time_t 타입으로 저장
	struct tm  tstruct;
	char       buf[80];
	tstruct = *localtime(&now);
	strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct); // YYYY-MM-DD.HH:mm:ss 형태의 스트링

	cout << buf;
}

아래와 같은 오류가 났다.

#define _CRT_SECURE_NO_WARNINGS

에러 예외처리를 해줘도 오류가 났다.

 

localtime 함수는 Unsafe하다고 한다. 그래서 localtime_s 함수를 써야한다.

 

localtime_s 함수 – 언제나 휴일

errno_t localtime_s(struct tm *tmp, const time_t *timer); 초단위 시간으로 지역 일시를 구하는 함수 입력 매개 변수 리스트 tm 변환한 지역 시각을 설정할 메모리 주소 timer 초단위 시간 반환 값 에러 번호 사

ehpub.co.kr

 

C언어] localtime_s 함수 사용법: 비주얼 Visual C 2005 이상에서

localtime 이라는 함수로 현재 시각을 구할 수 있지만, 비주얼C 2005 이상의 버전에서는 보안이 강화된 localtime_s 라는 함수를 사용합니다. 그렇지 않으면 localtime_s.cpp(11) : warning C4996: 'localtime': This func

mwultong.blogspot.com

#include <iostream>
#include <time.h>
#include <string>
#include <stdio.h>

using namespace std;

int main() {
	time_t now = time(NULL); // 현재 연월일 및 시각을 초 단위로 얻기
	struct tm tstruct;	
	char buf[80]; // 얻은 연월일 및 시각을 저장할 배열

	localtime_s(&tstruct, &now);	// 초 단위의 시간을 분리하여 구조체에 넣기
	// strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct); // 연-월-일.시:분:초
	strftime(buf, sizeof(buf), "%Y-%m-%d", &tstruct); // 포맷을 정해줌. 연-월-일

	cout << buf;
	return 0;
}

결과가 나왔다.

반응형
profile

Limetime's TimeLine

@Limetime

포스팅이 좋았다면 "공감❤️" 또는 "구독👍🏻" 해주세요!