VC++/ATL中获取当前日期并转换为字符串的完整实现方案
使用示例: - 获取当前日期:CString today = CDateTimeUtils::GetCurrentDateString();
- 获取完整时间戳:CString now = CDateTimeUtils::GetCurrentDateTimeString();
该方案封装了SYSTEMTIME操作,提供线程安全的静态方法,支持标准日期格式输出。初始化SYSTEMTIME结构体时使用{0}清零确保安全
- #pragma once
- #include <atlstr.h>
- class CDateTimeUtils {
- public:
- // 获取当前日期字符串(格式:YYYY-MM-DD)
- static CString GetCurrentDateString() {
- SYSTEMTIME st = {0};
- GetLocalTime(&st);
-
- CString strDate;
- strDate.Format(_T("%04d-%02d-%02d"),
- st.wYear, st.wMonth, st.wDay);
- return strDate;
- }
- // 获取当前日期时间字符串(格式:YYYY-MM-DD HH:MM:SS)
- static CString GetCurrentDateTimeString() {
- SYSTEMTIME st = {0};
- GetLocalTime(&st);
-
- CString strDateTime;
- strDateTime.Format(_T("%04d-%02d-%02d %02d:%02d:%02d"),
- st.wYear, st.wMonth, st.wDay,
- st.wHour, st.wMinute, st.wSecond);
- return strDateTime;
- }
- };
复制代码
|