Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use localtime_s with a pointer in c++

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

like image 217
kevin haysmer Avatar asked Feb 07 '16 19:02

kevin haysmer


People also ask

Why does Localtime return a pointer?

The pointer returned by localtime (and some other functions) are actually pointers to statically allocated memory. So you do not need to free it, and you should not free it. This structure is statically allocated and shared by the functions gmtime and localtime.

How to use local time in C?

C library function - localtime() The C library function struct tm *localtime(const time_t *timer) uses the time pointed by timer to fill a tm structure with the values that represent the corresponding local time. The value of timer is broken up into the structure tm and expressed in the local time zone.

What does localtime Return in C?

The localtime( ) function return the local time of the user i.e time present at the task bar in computer.


1 Answers

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;
}
like image 170
Christopher Oicles Avatar answered Oct 14 '22 11:10

Christopher Oicles