Get current date and time in C++

Parag katoch 81 Reputation points
2020-12-21T13:55:52.133+00:00

I have tried multiple ways to get date and time with ctype and localtime but I get error that The variable or function maybe unsafe and I thingk it is there for a reason.

Can anybody please tell me a valid way to get current date and time in C++ in Visual Studio 2019?

thankyou in advance!

Developer technologies C++
0 comments No comments
{count} votes

Accepted answer
  1. Jeanine Zhang-MSFT 11,356 Reputation points Microsoft External Staff
    2020-12-22T03:18:38.427+00:00

    Hi,

    I suggest you could try the following code:

    #include<iostream>  
    #include <stdio.h>        
    #include <time.h>     
    using namespace std;  
    int main() {  
    	time_t timetoday;  
    	time(&timetoday);  
    	cout << "Calendar date and time as per todays is : " << asctime(localtime(&timetoday));  
    	return 0;  
    }  
    

    I get error that The variable or function maybe unsafe and I thingk it is there for a reason.

    According to your description, is the error you encountered is "C4996"? I suggest you could try to add the following code:

    #pragma warning(disable : 4996)  
    

    For more details I suggest you could refer to the Doc:

    And you could also try to use asctime_s and localtime_s:

    #include <time.h>  
    #include <stdio.h>  
      
    struct tm newtime;  
    __time32_t aclock;  
      
    int main( void )  
    {  
       char buffer[32];  
       errno_t errNum;  
       _time32( &aclock );   
       _localtime32_s( &newtime, &aclock );   
       errNum = asctime_s(buffer, 32, &newtime);  
         
       printf( "Current date and time: %s", buffer );  
       return 0;  
    }  
    

    Best Regards,

    Jeanine


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. RLWA32 49,536 Reputation points
    2020-12-21T14:00:21.323+00:00

    For localtime, the cause of the message is right in the documentation - localtime-localtime32-localtime64
    It says "More secure versions of these functions are available; see localtime_s, _localtime32_s, _localtime64_s."

    1 person found this answer helpful.
    0 comments No comments

  2. Ahmed Saber 1 Reputation point
    2021-11-13T21:58:19.027+00:00

    Look at this example :-
    https://pastebin.com/8RvKStiv

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.