Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C++
Tip/Trick

C++ function to convert a date time value into different date formats

Rate me:
Please Sign up or sign in to vote.
3.40/5 (3 votes)
19 Aug 2013CPOL 29.1K   8   5
A function which returns date in different formats base on the input given

Introduction

A C++ function which takes standard time-stamp and a date-time format string(in which you wants the output) as input and format and returns the date in required format. 

Example:

  • formatDateTime( tDepTime, "CCYY-MM-DD hh:mm:ss" ), Output: 2013-08-19 03:00:00 
  • formatDateTime( tDepTime, "MMMM DD, CCYY - HH:mm:ss" ), Output: August 19, 2013 - 03:00:00  
  • formatDateTime( tDepTime, "DDDD MMMM D, CCYY - HH:mm:ss" )Output:  Monday  August 19, 2013 - 03:00:00 
  • formatDateTime( tDepTime, "CCYY/MM/DD HH:mm:ss" ), Output: 2013/08/19 03:00:00  
  • formatDateTime( tDepTime, "CCYYMMDDHHmm" ), Output: 201308190300 
  • formatDateTime( tDepTime, "CCYYMMDDHHmm" ), Output: 20130819  
  • formatDateTime( tDepTime, "MMDD" )Output: 0819  

 etc.... 

Using the code 

C++
char * FormatDateTime(__time32_t TimeStamp, char *pszFormatString)
{
    char pszRetBuf[100] = "";
    int iRetBufSize = 100; 

    struct tm today;
    if ( TimeStamp == 0x00 )
    {
        strcpy_s( pszRetBuf, iRetBufSize, "** No Date/Time **" );
        return pszRetBuf;
    }
    else
    {
        _localtime32_s( &today, &TimeStamp );
    }

    //In case you need whole month in output
    char szMonths[12][10]       = {"January","February","March","April",
      "May","June","July","August","September",
      "October","November","December"};
    char szShortMonths[12][4]   = {"Jan","Feb","Mar","Apr",
      "May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
    char szShortMonths[12][4]   = {"Jan","Feb","Mar","Apr",
      "May","Jun","Jul","Aug",
      "Sep","Oct","Nov","Dec"};
    char szDays[7][10]          = {"Sunday","Monday","Tuesday",
      "Wednesday","Thursday","Friday","Saturday"};
    char szShortDays[7][4]      = {"Sun","Mon","Tue","Wed",
      "Thu","Fri","Sat"};
    char szAMPM[2][3]           = {"AM","PM"};
    int aiMnemonic[13]          = {2,2,2,2,2,4,2,4,3,2,4,3,2};
    char szMnemonics[13][5]     = {"hh","HH","mm","ss",
      "AP","CCYY","YY","MMMM",
      "MMM","MM","DDDD","DDD","DD"};
    char szMasks[13][5]         = {"%02d","%02d","%02d","%02d",
      "%s","%04d","%02d","%s","%s",
      "%02d","%s","%s","%02d"};
    int iYear = today.tm_year + 1900;
    if ( iYear < 1995 ) //|| iYear > 2030 )
        iYear = 0;
    int iMonth = today.tm_mon + 1;
    if ( iMonth < 1 || iMonth > 12 )
        iMonth = 0;
    int iDay = today.tm_mday;
    if ( iDay < 0 || iDay > 31 )
        iDay = 0;
    int iWeekDay = today.tm_wday;
    if ( iWeekDay > 6 )
        iWeekDay = 0;
    int iHour = today.tm_hour;
    int iMinute = today.tm_min;
    int iSecond = today.tm_sec;

    if ( iYear == 0 || iMonth == 0 || iDay == 0 )
    {
    strcpy_s( pszRetBuf, iRetBufSize, "** No Date/Time **" );
    return pszRetBuf;
    }

    void * vpReplace[13];
    vpReplace[0] = (void *)(( iHour > 12 ) ? iHour - 12 : iHour );
    vpReplace[1] = (void *)iHour;
    vpReplace[2] = (void *)iMinute;
    vpReplace[3] = (void *)iSecond;
    vpReplace[4] = ( iHour > 12 ) ? szAMPM[1] : szAMPM[0];
    vpReplace[5] = (void *)iYear;
    vpReplace[6] = (void *)(iYear - 2000);
    vpReplace[7] = szMonths[iMonth-1];
    vpReplace[8] = szShortMonths[iMonth-1];
    vpReplace[9] = (void *)iMonth;
    vpReplace[10] = szDays[iWeekDay];
    vpReplace[11] = szShortDays[iWeekDay];
    vpReplace[12] = (void *)iDay;

    char szDateOutput[1024];    // leave lots of working space!
    char szDateFormatTemp[20];
    memset( szDateOutput, 0x00, 1024 );

    // work from left to right, and replace characters as we find them.
    int iSource = 0;
    int iSourceLength = (int)strlen( pszFormatString );
    int iOutput = 0;
    int iMnemonic = 0;
    bool fReplaced;
    for ( iSource = 0; iSource < iSourceLength; iSource++ )
    {
        fReplaced = false;
        for ( iMnemonic = 0; iMnemonic < 13; iMnemonic++ )
        {
            if ( strncmp( &pszFormatString[iSource], 
                      szMnemonics[iMnemonic], aiMnemonic[iMnemonic] ) == 0 )
            {
                // since it matches - and since the order or length is reversed - go ahead and replace               
                sprintf_s( szDateFormatTemp, szMasks[iMnemonic], vpReplace[iMnemonic] );
                strcat_s( szDateOutput, szDateFormatTemp );
                iSource += ( aiMnemonic[iMnemonic] - 1 );
                fReplaced = true;
                iMnemonic = 20;
                iOutput = (int)strlen( szDateOutput );
                if ( iOutput > 900 )    // give ourselves breathing space!!!
                    ThrowException( "CCQData::formatDateTime", 
                      "Date Output Buffer in danger of causing memory exception", 3, __LINE__ );
                }
            }

        if (!fReplaced)
            szDateOutput[iOutput++] = pszFormatString[iSource];
    }

    strcpy_s( pszRetBuf, iRetBufSize, szDateOutput );
    return pszRetBuf;
}   

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Nihilent Technologies Pvt Ltd
South Africa South Africa
I am working with Nihilent Technologies Pvt Ltd.I have worked on Banking and Finance domain, mainly in Cash Management and Repo Trading.
Technologies:-
My technological forte is VC++, C++, Win32, MFC, ATL/COM, C#.NET Windows Application, C, WebSphere MQ and DB2.
Specialties
Domain:-
BFS (Cash Management and Repo Trading)
Technologies:-
C, C++, VC++, Win32, MFC, ATL/COM, WebSphere MQ, DB2

Comments and Discussions

 
GeneralMy vote of 1 Pin
vincenzo panella31-Dec-14 13:27
vincenzo panella31-Dec-14 13:27 
QuestionComments Pin
Mike Diack19-Aug-13 21:51
Mike Diack19-Aug-13 21:51 
AnswerRe: Comments Pin
Ritesh_Singh19-Aug-13 22:04
Ritesh_Singh19-Aug-13 22:04 
Questionreturn value bug Pin
pj220_200619-Aug-13 17:16
pj220_200619-Aug-13 17:16 
AnswerRe: return value bug Pin
Ritesh_Singh19-Aug-13 22:05
Ritesh_Singh19-Aug-13 22:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.