Cara untuk mendapatkan waktu saat ini dan tanggal di C++?

Apakah ada cross-platform cara untuk mendapatkan tanggal dan waktu saat ini di C++?

Mengomentari pertanyaan (3)
Larutan

Dalam C++ 11 anda dapat menggunakan [std::chrono::system_clock::sekarang()][1]

Contoh (disalin dari [en.cppreference.com][2]):


#include 
#include 
#include     

int main()
{
    auto start = std::chrono::system_clock::now();
    // Some computation here
    auto end = std::chrono::system_clock::now();

    std::chrono::duration elapsed_seconds = end-start;
    std::time_t end_time = std::chrono::system_clock::to_time_t(end);

    std::cout 
Komentar (7)

C++ saham tanggal/waktu fungsi dengan C. [tm struktur][1] mungkin adalah cara termudah untuk C++ programmer untuk bekerja dengan - berikut cetak hari ini's upload:


#include 
#include 

int main() {
    std::time_t t = std::time(0);   // get time now
    std::tm* now = std::localtime(&t);
    std::cout tm_year + 1900) 
Komentar (11)

Anda dapat mencoba cross-platform berikut kode untuk mendapatkan current date/time:


#include 
#include 
#include 
#include 

// Get current date/time, format is YYYY-MM-DD.HH:mm:ss
const std::string currentDateTime() {
    time_t     now = time(0);
    struct tm  tstruct;
    char       buf[80];
    tstruct = *localtime(&now);
    // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
    // for more information about date/time format
    strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);

    return buf;
}

int main() {
    std::cout 
Komentar (4)

std C perpustakaan menyediakan time(). Ini adalah detik dari zaman dan dapat dikonversi ke date dan H:M:S menggunakan fungsi-fungsi standar C. Meningkatkan juga memiliki waktu/tanggal library yang anda dapat memeriksa.

time_t  timev;
time(&timev);
Komentar (3)

C++ standar library tidak memberikan tanggal yang tepat jenis. C++ mewarisi struktur dan fungsi tanggal dan waktu manipulasi dari C, bersama dengan beberapa tanggal/waktu input dan output fungsi yang memperhitungkan lokalisasi.


// Current date/time based on current system
time_t now = time(0);

// Convert now to tm struct for local timezone
tm* localtm = localtime(&now);
cout 
Komentar (0)

Baru, jawaban untuk sebuah pertanyaan lama:

Pertanyaan tidak menentukan apa yang di timezone. Ada dua yang wajar kemungkinan:

  1. Dalam UTC.
  2. Dalam komputer's zona waktu lokal.

1, anda dapat menggunakan [tanggal ini perpustakaan][1] dan program berikut:


#include "date.h"
#include 

int
main()
{
    using namespace date;
    using namespace std::chrono;
    std::cout 
Komentar (2)

(Untuk sesama karyawan google)

Ada juga Boost::date_time :

#include 

boost::posix_time::ptime date_time = boost::posix_time::microsec_clock::universal_time();
Komentar (0)

auto time = std::time(nullptr);
std::cout 
Komentar (0)
#include 
#include 

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;

  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  printf ( "Current local time and date: %s", asctime (timeinfo) );

  return 0;
} 
Komentar (0)

Ya dan anda dapat melakukannya dengan format aturan yang ditentukan oleh saat ini-dijiwai lokal:


#include 
#include 
#include 

class timefmt
{
public:
    timefmt(std::string fmt)
        : format(fmt) { }

    friend std::ostream& operator 
Komentar (4)

anda bisa menggunakan C++ 11 waktu kelas:


    #include 
    #include 
    using namespace std;

    int main() {

       time_t now = chrono::system_clock::to_time_t(chrono::system_clock::now());
       cout 
Komentar (0)

Ada's selalu __TIMESTAMP__ preprocessor makro.


#include 

using namespace std

void printBuildDateTime () {
    cout 
Komentar (3)

Anda juga dapat langsung menggunakan ctime():

#include 
#include 

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;

  time ( &rawtime );
  printf ( "Current local time and date: %s", ctime (&rawtime) );

  return 0;
} 
Komentar (1)

Saya menemukan link ini cukup berguna untuk implementasi saya: C++ Tanggal dan Waktu

Berikut ini's kode yang saya gunakan dalam implementasi saya, untuk mendapatkan yang jelas "YYYYMMDD HHMMSS" format output. Kode param adalah untuk beralih antara waktu UTC dan waktu lokal. Anda dapat dengan mudah memodifikasi kode saya untuk kebutuhan anda.


#include 
#include 

using namespace std;

/**
 * This function gets the current date time
 * @param useLocalTime true if want to use local time, default to false (UTC)
 * @return current datetime in the format of "YYYYMMDD HHMMSS"
 */

string getCurrentDateTime(bool useLocalTime) {
    stringstream currentDateTime;
    // current date/time based on current system
    time_t ttNow = time(0);
    tm * ptmNow;

    if (useLocalTime)
        ptmNow = localtime(&ttNow);
    else
        ptmNow = gmtime(&ttNow);

    currentDateTime tm_year;

    //month
    if (ptmNow->tm_mon < 9)
        //Fill in the leading 0 if less than 10
        currentDateTime tm_mday < 10)
        currentDateTime 
Komentar (6)

Ini disusun untuk saya di Linux (RHEL) dan Windows (x64) menargetkan g++ dan OpenMP:


#include 
#include 
#include 
#include 

////////////////////////////////////////////////////////////////////////////////
//
//  Reports a time-stamped update to the console; format is:
//       Name: Update: Year-Month-Day_of_Month Hour:Minute:Second
//
////////////////////////////////////////////////////////////////////////////////
//
//  [string] strName  :  name of the update object
//  [string] strUpdate:  update descripton
//          
////////////////////////////////////////////////////////////////////////////////

void ReportTimeStamp(string strName, string strUpdate)
{
    try
    {
        #ifdef _WIN64
            //  Current time
            const time_t tStart = time(0);
            //  Current time structure
            struct tm tmStart;

            localtime_s(&tmStart, &tStart);

            //  Report
            cout 
Komentar (0)

http://www.cplusplus.com/reference/ctime/strftime/

Ini built-in tampaknya menawarkan satu set yang wajar dari opsi.

Komentar (2)

The ffead-cpp menyediakan beberapa utilitas kelas untuk berbagai tugas, satu kelas tersebut adalah Tanggal kelas yang menyediakan banyak fitur yang tepat dari Tanggal operasi untuk tanggal aritmatika, ada's juga Timer kelas yang disediakan untuk waktu operasi. Anda dapat melihat hal yang sama.

Komentar (0)

Ini bekerja dengan G++ I'm tidak yakin jika ini akan membantu anda. Output Program:

The current time is 11:43:41 am
The current date is 6-18-2015 June Wednesday 
Day of month is 17 and the Month of year is 6,
also the day of year is 167 & our Weekday is 3.
The current year is 2015.

Kode :


#include 
#include 
#include 
#include 
#include 

using namespace std;

const std::string currentTime() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%H:%M:%S %P", &tstruct);
return buf;
}

const std::string currentDate() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%B %A ", &tstruct);
return buf;
}

int main() {
    cout 
Komentar (1)

Anda dapat menggunakan kode berikut untuk mendapatkan sistem saat ini tanggal dan waktu dalam C++ :


#include 
#include  //It may be #include  or any other header file depending upon
                 // compiler or IDE you're using 
using namespace std;

int main() {
   // current date/time based on current system
   time_t now = time(0);

   // convert now to string form
   string dt = ctime(&now);

   cout 
Komentar (0)

localtime_s() versi:

#include 
#include 

int main ()
{
  time_t current_time;
  struct tm  local_time;

  time ( &current_time );
  localtime_s(&local_time, &current_time);

  int Year   = local_time.tm_year + 1900;
  int Month  = local_time.tm_mon + 1;
  int Day    = local_time.tm_mday;

  int Hour   = local_time.tm_hour;
  int Min    = local_time.tm_min;
  int Sec    = local_time.tm_sec;

  return 0;
} 
Komentar (0)