1cfd3bbb56
Topic_CSS/Topic_HTML/Topic_JavaScript/Topic_Prompt/Topic_Comfyui 등 기존 카테고리 폴더를 정리하고, Topic_Graphic/Dev 등 신규 산출물과 Topics 내부 세션/메모리 기록을 동기화.
78 lines
5.2 KiB
Markdown
78 lines
5.2 KiB
Markdown
---
|
|
id: cpp-date
|
|
title: "C++ Date and Time"
|
|
category: "Programming_Language"
|
|
status: "draft"
|
|
verification_status: "conceptual"
|
|
canonical_id: ""
|
|
aliases: ["ctime library", "mktime", "strftime", "clock() timing", "C++ 날짜와 시간"]
|
|
duplicate_of: ""
|
|
source_trust_level: "B"
|
|
confidence_score: 0.86
|
|
created_at: 2026-07-04
|
|
updated_at: 2026-07-04
|
|
review_reason: ""
|
|
merge_history: []
|
|
tags: ["cpp", "programming-language", "w3schools", "date-time", "ctime"]
|
|
raw_sources: ["https://www.w3schools.com/cpp/cpp_date.asp"]
|
|
applied_in: []
|
|
github_commit: ""
|
|
---
|
|
|
|
# [[CPP Date and Time]]
|
|
|
|
## 🎯 한 줄 통찰 (One-line insight)
|
|
`mktime()` isn't just for CONVERTING a manually-built date into a timestamp — the source shows it also SELF-CORRECTS invalid dates (setting day-of-month to 32 and calling `mktime()` normalizes it into a valid date, unlike `asctime()` which just displays "32" verbatim without correcting it) and FILLS IN derived fields like the weekday (`tm_wday`) automatically, meaning `mktime()` does double duty as both a converter and a date-validator/completer that the more display-focused functions (`ctime()`, `asctime()`) don't provide. [S1]
|
|
|
|
## 🧠 핵심 개념 (Core concepts)
|
|
- **Two date representations** — `time_t` (a single-number timestamp, easy for calculation) vs. `struct tm` (a structure with separate `tm_sec`/`tm_min`/`tm_hour`/`tm_mday`/`tm_mon`/`tm_year`/`tm_wday`/`tm_yday` fields, easier for humans to specify). [S1]
|
|
- **Offset conventions to remember** — hours are 24-hour format; months are 0-11 (December = 11, not 12); years are relative to 1900 (2024 = 124). [S1]
|
|
- **`mktime()`** — converts a `struct tm` INTO a `time_t` timestamp; ALSO fills in `tm_wday`/`tm_yday` automatically and CORRECTS invalid date values (e.g. day 32 gets normalized). [S1]
|
|
- **`localtime()` / `gmtime()`** — convert a timestamp INTO a `struct tm`, in local time zone or GMT respectively; return a POINTER, so dereference to get a stable copy if needed. [S1]
|
|
- **`ctime()` / `asctime()`** — display a date as a fixed-format string (from a timestamp or a `struct tm` respectively); `asctime()` does NOT correct invalid dates, unlike `mktime()`. [S1]
|
|
- **`strftime()`** — formats a date into a CUSTOM string layout using format specifiers (`%B`, `%H`, `%Y`, etc.), writing into a caller-provided `char` buffer. [S1]
|
|
- **`difftime()`** — measures SECONDS between two timestamps, for date-level time differences. [S1]
|
|
- **`clock()`** — measures short program-execution intervals in "clocks" (via `clock_t`), converted to seconds by dividing by `CLOCKS_PER_SEC`; more precise than `difftime()` for measuring runtime performance. [S1]
|
|
|
|
## 📖 세부 내용 (Details)
|
|
- `mktime()` correcting an invalid date before display: `struct tm datetime; datetime.tm_mday = 32; /* other fields set */ mktime(&datetime); cout << asctime(&datetime); // normalized to a valid date`. [S1]
|
|
- Formatting a date multiple ways with `strftime()`: `strftime(output, 50, "%B %e, %Y", &datetime); // "December 17, 2023" strftime(output, 50, "%I:%M:%S %p", &datetime); // "12:30:01 PM"`. [S1]
|
|
- Measuring execution time precisely with `clock()`: `clock_t before = clock(); /* work */ clock_t duration = clock() - before; cout << (float)duration / CLOCKS_PER_SEC << " seconds";` — casting to `float` BEFORE dividing avoids integer-division truncation. [S1]
|
|
|
|
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
|
- **mktime()는 변환뿐 아니라 날짜 보정과 요일 계산까지 수행**: 32일처럼 잘못된 날짜 값을 정규화하고 tm_wday/tm_yday를 자동으로 채워준다는 점이 단순 표시 함수인 asctime()/ctime()과의 핵심 차이로 확인됨. [S1]
|
|
- **clock() 나눗셈 시 정수 나눗셈 주의**: CLOCKS_PER_SEC로 나누기 전에 float/double로 캐스팅하지 않으면 정수 나눗셈으로 소수점이 잘려나간다는 점이 명시적으로 경고됨. [S1]
|
|
|
|
## 🛠️ 적용 사례 (Applied in summary)
|
|
100,000번 반복 루프의 실행 시간을 clock()으로 측정하는 예제가 프로그램 성능 측정의 실전 활용 사례로 원문에 직접 제시됨. [S1]
|
|
|
|
## 💻 코드 패턴 (Code patterns)
|
|
Measuring program execution time precisely with clock(), casting before dividing (C++):
|
|
```cpp
|
|
clock_t before = clock();
|
|
int k = 0;
|
|
for (int i = 0; i < 100000; i++) {
|
|
k += i;
|
|
}
|
|
clock_t duration = clock() - before;
|
|
cout << "Duration: " << (float)duration / CLOCKS_PER_SEC << " seconds";
|
|
```
|
|
|
|
## ✅ 검증 상태 및 신뢰도
|
|
- **상태:** draft
|
|
- **검증 단계:** conceptual
|
|
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
|
- **신뢰 점수:** 0.86
|
|
- **중복 검사 결과:** 신규 생성 (New discovery)
|
|
|
|
## 🔗 지식 그래프 (Knowledge Graph)
|
|
- **상위/루트:** [[C++ Tutorial]]
|
|
- **관련 개념:** [[CPP User Input]], [[CPP Pointers Dereference]], [[CPP Errors]]
|
|
- **참조 맥락:** 사용자 입력 및 날짜 섹션 마지막 — 에러 및 디버깅(Errors & Debugging) 섹션으로 이어짐.
|
|
|
|
## 📚 출처 (Sources)
|
|
- [S1] W3Schools — C++ Date and Time — https://www.w3schools.com/cpp/cpp_date.asp
|
|
|
|
## 📝 변경 이력 (Change history)
|
|
- 2026-07-04: Initial draft synthesized from the W3Schools "C++ Date and Time" page (Astra wiki-curation, P-Reinforce v3.1 format).
|