0

I am using below method to validate Date. How to format month in string ?

bool CDateTime :: IsValidDate(char* pcDate) //pcDate = 25-Jul-2012 15:08:23
{
    bool bVal = true;
    int iRet = 0;
    struct tm tmNewTime;   

    iRet = sscanf_s(pcDate, "%d-%d-%d %d:%d:%d", &tmNewTime.tm_mon, &tmNewTime.tm_mday, &tmNewTime.tm_year, &tmNewTime.tm_hour, &tmNewTime.tm_min, &tmNewTime.tm_sec);
    if (iRet == -1)
        bVal = false;

    if (bVal == true)
    {
        tmNewTime.tm_year -= 1900;
        tmNewTime.tm_mon -= 1;
        bVal = IsValidTm(&tmNewTime);
    }
    return bVal;

}
Bokambo
  • 4,204
  • 27
  • 79
  • 130

2 Answers2

1

Using strptime:

#include <time.h>
char *str = "25-Jul-2012 15:08:23";
struct tm tm;
if (strptime (str, "%d-%b-%Y %H:%M:%S", &tm) == NULL) {
   /* Bad format !! */
}
perreal
  • 94,503
  • 21
  • 155
  • 181
-1

The C++11 way of doing this is:

#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>

int main()
{
    auto now = std::chrono::system_clock::now();
    auto now_c = std::chrono::system_clock::to_time_t(now);

    std::cout << "Now is " << std::put_time(std::localtime(&now_c), "%d-%b-%Y %H:%M:%S") << '\n';
}

Note: The stream I/O manipulator std::put_time is not implemented fully in all compilers yet. GCC 4.7.1 does not have it for example.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621