首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

VC++ CTime 獲取系統時間:必須先調用 GetCurrentTime 初始化對象

     編輯:程式設計綜合問答

錯誤代碼


CTime time;
CString strDate;
strDate = time.Format("%d年%d月%d日", time.GetYear(), time.GetMonth(), time.GetDay());
// time 未初始化,默認 1970-01-01

正確用法


CTime time = CTime::GetCurrentTime();  // 靜態方法獲取當前時間
CString strDate;
strDate.Format(_T("%d年%02d月%02d日"), time.GetYear(), time.GetMonth(), time.GetDay());
AfxMessageBox(strDate);

補充

  • `CTime::GetCurrentTime()` 返回當前本地時間對象。
  • `Format` 為實例方法,需對象已初始化。
  • VS2010 無 `GetCurrentTime` 非靜態成員,僅有靜態 `CTime::GetCurrentTime()`。
  • 格式字符串 `%02d` 補零對齊。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved