簡體   English   中英

如何獲取當前時間和日期 C++ UTC time not local

[英]How to get the current time and date C++ UTC time not local

我想知道如何在 C++ Linux中獲取 UTC 時間或任何其他時區(不僅僅是本地時間)。

我想做類似的事情: int Minutes = time.now(Minutes)來獲取和存儲那個確切時間的年、月、日、小時、分鍾和秒。
我怎么能這樣做?

我需要多次重復這個過程; 我想知道最新最好的方法。

您正在time.h庫中查找gmtime函數,該函數為您提供 UTC 時間。 下面是一個例子:

#include <stdio.h>      /* printf */
#include <time.h>       /* time_t, struct tm, time, gmtime */

int main ()
{
  time_t rawtime;
  struct tm * ptm;
  // Get number of seconds since 00:00 UTC Jan, 1, 1970 and store in rawtime
  time ( &rawtime );
  // UTC struct tm
  ptm = gmtime ( &rawtime );
  // print current time in a formatted way
  printf ("UTC time: %2d:%02d\n", ptm->tm_hour, ptm->tm_min);

  return 0;
}

看看這些來源:

如果你想要面向linux的解決方案,你可以使用c++中的系統命令

例如

    #include <iostream>
    #include <sstream>        //for stringstream function to store date and time
    
    using namespace std;
    
    int main()
    {
        const char *date_now = "date -u";       //linux command to get UTC time is "date -u"
        stringstream s;
        s << system(date_now);        //to store output of system("date_now") to s;
        cout << s.str() << endl;        //to print the string in s
        
        return 0;
    }

在 linux 終端中查看“date --help”以獲取更多與日期和時間相關的命令。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM