how to use localtime_s with a pointer in c++

kevin haysmer picture kevin haysmer · Feb 7, 2016 · Viewed 16.8k times · Source

I am working with a function in C++ to help get the integer for the month. I did some searching and found one that uses localtime but I do not want to set it up to remove warnings so I need to use localtime_s. but when I use that my pointer no longer works and I need someone to help me find what I am missing with the pointer.

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <Windows.h>
#include "FolderTask.h"
#include <ctime> //used for getMonth
#include <string>
#include <fstream>

int getMonth()
{
    struct tm newtime;
    time_t now = time(0);
    tm *ltm = localtime_s(&newtime,&now);
    int Month = 1 + ltm->tm_mon;
    return Month;
}

the error I am getting is:

error C2440: 'initializing': cannot convert from 'errno_t' to 'tm *' note: Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast

Answer

Christopher Oicles picture Christopher Oicles · Feb 7, 2016

It looks like you're using Visual C++, so localtime_s(&newtime,&now); fills in the newtime struct with the numbers you want. Unlike the regular localtime function, localtime_s returns an error code.

So this is a fixed version of the function:

int getMonth()
{
    struct tm newtime;
    time_t now = time(0);
    localtime_s(&newtime,&now);
    int Month = 1 + newtime.tm_mon;
    return Month;
}