从VC6迁移到VS2005 - LocalTime

来源:互联网 发布:sha256代码java 编辑:程序博客网 时间:2024/04/28 10:16

    我们在编程时,会使用比较多的日期、时间等值;其中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


    上一篇博文《从VC6迁移到VS2005 - METHOD》,我们知道要使用安全函数“*_s”。


    需要更改的函数主要为: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);



    以下程序在VS2005以上版本编译通过:

/*  *  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;}


0 0
原创粉丝点击