在 C++ 中获取当前日期和时间

Hui Liu-MSFT 48,676 信誉分 Microsoft 外部员工
2024-03-12T06:49:31.38+00:00

我尝试了多种方法来使用 ctypelocaltime 获取日期和时间,但我收到错误,该变量或函数可能不安全,我 thingk 它的存在是有原因的。

任何人都可以告诉我在Visual Studio 2019中获取C++当前日期和时间的有效方法吗?

先谢谢你!

Note:此问题总结整理于: Get current date and time in C++

开发人员技术 C++
0 个注释 无注释
{count} 票

接受的答案
  1. 匿名
    2024-03-12T08:47:53.2466667+00:00

    你好

    我建议您可以尝试以下代码:

    #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;  
    }  
    

    我收到错误,变量或函数可能不安全,我担心它的存在是有原因的。

    根据您的描述,您遇到的错误是“C4996”吗?我建议您可以尝试添加以下代码:

    #pragma warning(disable : 4996)  
    

    有关更多详细信息,我建议您可以参考文档

    您也可以尝试使用asctime_slocaltime_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;  
    }  
    

    如果答案是正确的,请点击“接受答案”并点赞。 如果您对此答案还有其他疑问,请点击“评论”。

    注意:如果您想接收相关电子邮件,请按照我们的文档中的步骤启用电子邮件通知 此线程的通知。

    0 个注释 无注释

0 个其他答案

排序依据: 非常有帮助

你的答案

问题作者可以将答案标记为“接受的答案”,这有助于用户了解已解决作者问题的答案。