728x90
반응형
개요
C 언어에서 문자열 형태의 날짜와 현재 시간을 비교하여 만료일까지 남은 일수를 계산하는 방법을 다룬다. 이 기술은 라이센스 검증, 이벤트 타이머, 계약 만료 알림 등 다양한 시스템에서 활용될 수 있다.
설명
C 언어에서 날짜와 시간을 처리하기 위해서는 time.h
라이브러리를 사용한다. 이 라이브러리는 시간 관련 구조체와 함수들을 제공하며, 특히 time_t
와 struct tm
타입을 통해 Unix epoch 시간(1970년 1월 1일부터 경과한 초 단위)과 사람이 읽을 수 있는 날짜 형식 간의 변환을 지원한다.
날짜 비교 과정은 크게 세 단계로 나뉜다:
- 문자열 형태의 목표 날짜를 epoch 시간으로 변환
- 현재 시간을 epoch 시간으로 변환 (시/분/초는 0으로 설정)
- 두 epoch 시간을 비교하여 남은 일수 계산
특징
strptime()
함수를 사용해 문자열 형태의 날짜를struct tm
구조체로 변환mktime()
함수로struct tm
구조체를 epoch 시간으로 변환- 정확한 날짜 비교를 위해 시간/분/초 값을 0으로 설정
difftime()
함수로 두 시간 사이의 차이를 초 단위로 계산- 초 단위 차이를 하루의 초(86400)로 나누어 일수 계산
예제
아래 코드는 주어진 만료일("2026-06-12")과 현재 날짜를 비교하여 만료까지 남은 일수를 계산한다:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main(void) {
char* target_date = "2026-06-12";
time_t rawtime;
struct tm target_tm;
int day_remaining;
// 목표 날짜를 epoch 시간 형식으로 변환
memset(&target_tm, 0, sizeof(struct tm));
strptime(target_date, "%Y-%m-%d", &target_tm);
time_t target_epoch = mktime(&target_tm);
printf("만료 날짜 : %04d-%02d-%02d\n", target_tm.tm_year+1900, target_tm.tm_mon+1, target_tm.tm_mday);
// 현재 시간 가져오기
memset(&target_tm, 0, sizeof(struct tm));
time(&rawtime);
target_tm = *(localtime(&rawtime));
// target_tm의 시간, 분, 초 필드를 0으로 설정
target_tm.tm_hour = target_tm.tm_min = target_tm.tm_sec = 0;
// 현재 날짜를 시간, 분, 초 없이 epoch 시간 형식으로 변환
time_t current_date_epoch = mktime(&target_tm);
printf("현재 날짜 : %04d-%02d-%02d\n", target_tm.tm_year+1900, target_tm.tm_mon+1, target_tm.tm_mday);
// 현재 날짜와 목표 날짜 비교
day_remaining = difftime(target_epoch, current_date_epoch) / (60 * 60 * 24);
if(day_remaining >= 0) {
printf("만료까지 %d일 남았습니다.\n", day_remaining);
} else {
printf("날짜가 만료되었습니다.\n");
}
return 0;
}
실행 결과 예시 (2025년 3월 31일 기준):
만료 날짜 : 2026-06-12
현재 날짜 : 2025-03-31
만료까지 438일 남았습니다.
결론
C 언어에서 날짜 비교와 만료일 계산은 time.h
라이브러리 함수들을 활용하여 효과적으로 구현할 수 있다. 특히 정확한 날짜 비교를 위해서는 시간/분/초를 0으로 설정하여 순수하게 날짜만 비교하는 접근 방식이 중요하다. 이러한 날짜 처리 기법은 소프트웨어 라이센스, 구독 서비스, 계약 관리 등 다양한 응용 프로그램에서 유용하게 활용될 수 있다.
참고자료
- C Library - <time.h>: https://www.tutorialspoint.com/c_standard_library/time_h.htm
- strptime() Documentation: https://man7.org/linux/man-pages/man3/strptime.3.html
- difftime() Documentation: https://en.cppreference.com/w/c/chrono/difftime
728x90
반응형
'Programming > C' 카테고리의 다른 글
pthread의 이해와 구현: 멀티스레딩 프로그래밍의 기초 (0) | 2025.04.08 |
---|---|
C언어의 #error와 #line 전처리기 지시자 (0) | 2025.04.03 |
OpenSSL을 이용한 RSA 암호화/복호화 구현 (0) | 2025.04.01 |
C언어로 인터넷 연결 상태 확인하기 (2) | 2025.03.29 |
cJSON을 활용한 JSON 파싱 (2) | 2025.03.25 |