我们在编程时,会使用比较多的日期、时间等值;其中time、localtime是经常使用的!
time函数声明:
time_t time( time_t *timer );locatime结构声明:
struct tm *localtime( const time_t *timer );大部分我们需要输出一个像:xxxx-xx-xx格式的日期
下面的程序在VC6中调试通过:
/* * Gets the local system time * * Created on: 2011-12-24 * Author: xiaobin */ char *getLocalMachineTime() { struct tm *myTime; time_t long_time; time(&long_time); myTime = localtime(&long_time); char *result = NULL; result = (char *)malloc(1); int iYear = myTime->tm_year; iYear += 1900; char *myYear = (char *)malloc(5); myYear = _itoa(iYear, myYear, 10); strcpy(result, myYear); strncat(result, "-", 1); int iMonth = myTime->tm_mon; iMonth += 1; char *myMonth = (char *)malloc(3); if(iMonth < 10) { strcpy(myMonth, "0"); } _itoa(iMonth, myMonth, 10); strncat(result, myMonth, sizeof(myMonth)); strncat(result, "-", 1); int iDay = myTime->tm_mday; char *myDay = (char *)malloc(3); if(iDay < 10) { strcpy(myDay, "0"); } _itoa(iDay, myDay, 10); strncat(result, myDay, sizeof(myDay)); return result; }
2013-09-09
需要更改的函数主要为:localtime->localtime_s、_itoa->_itoa_s、strcpy->strcpy_s、strncat->strncat_s
localtime_s函数声明:
errno_t localtime_s( struct tm* _tm, const time_t *time );_itoa_s函数声明:
errno_t _itoa_s( int value, char *buffer, size_t sizeInCharacters, int radix );其中的radix参数为进制数:2,8,10,16进制等等
strcpy_s函数声明:
errno_t strcpy_s( char *strDestination, size_t numberOfElements, const char *strSource );strncat_s函数声明:
errno_t strncat_s( char *strDest, size_t numberOfElements, const char *strSource, size_t count );
/* * Gets the local system time * * Created on: 2011-12-24 * Author: xiaobin */ char *getLocalMachineTime() { struct tm myTime; time_t long_time; time(&long_time); localtime_s(&myTime, &long_time); char result[12]; int iYear = myTime.tm_year; iYear += 1900; char chYear[5]; _itoa_s(iYear, chYear, 5, 10); strcpy_s(result, chYear); strncat_s(result, "-", 1); int iMonth = myTime.tm_mon; iMonth += 1; char chZero[] = "0"; char chMonth[3]; _itoa_s(iMonth, chMonth, 3, 10); if(iMonth < 10) { strncat_s(result, chZero, 2); } strncat_s(result, chMonth, 2); strncat_s(result, "-", 1); int iDay = myTime.tm_mday; char chDay[3]; _itoa_s(iDay, chDay, 3, 10); if(iDay < 10) { strncat_s(result, chZero, 2); } strncat_s(result, chDay, 3); return result; }
// prjLocalDateTime.cpp : Defines the entry point for the console application. // /* * prjLocalDateTime.cpp * * Created on: 2011-12-24 * Author: xiaobin */ #include "stdafx.h" #include <comdef.h> #include "time.h" #include <stdlib.h> char *getLocalMachineTime(); int _tmain(int argc, _TCHAR* argv[]) { char dateChar[12]; char *temp = getLocalMachineTime(); strcpy(dateChar, temp); for(int i=0; i<12; i++){ printf("%c", dateChar[i]); } return 0; }