มีวิธีข้ามแพลตฟอร์มเพื่อรับวันที่และเวลาปัจจุบันใน C ++ หรือไม่
tmโครงสร้าง วิธี C ++ 11 ไม่เพียงให้ timestamp unix (เวลานับตั้งแต่ยุค) ถึงแม้ว่าคำถามเกี่ยวกับการรับวันที่และเวลา?
                มีวิธีข้ามแพลตฟอร์มเพื่อรับวันที่และเวลาปัจจุบันใน C ++ หรือไม่
tmโครงสร้าง วิธี C ++ 11 ไม่เพียงให้ timestamp unix (เวลานับตั้งแต่ยุค) ถึงแม้ว่าคำถามเกี่ยวกับการรับวันที่และเวลา?
                คำตอบ:
ใน C ++ 11 คุณสามารถใช้ std::chrono::system_clock::now()
ตัวอย่าง (คัดลอกมาจากen.cppreference.com ):
#include <iostream>
#include <chrono>
#include <ctime>    
int main()
{
    auto start = std::chrono::system_clock::now();
    // Some computation here
    auto end = std::chrono::system_clock::now();
    std::chrono::duration<double> elapsed_seconds = end-start;
    std::time_t end_time = std::chrono::system_clock::to_time_t(end);
    std::cout << "finished computation at " << std::ctime(&end_time)
              << "elapsed time: " << elapsed_seconds.count() << "s\n";
}ควรพิมพ์สิ่งนี้:
finished computation at Mon Oct  2 00:59:08 2017
elapsed time: 1.88232sstringจากstreamหรือวิธีการจัดรูปแบบที่ถูกต้องให้time_point<>ไปข้างหน้าและถามคำถามอื่นหรือ google หลังจากนั้น
                    C ++ แบ่งปันฟังก์ชั่นวันที่ / เวลากับ C โครงสร้าง tmน่าจะง่ายที่สุดสำหรับโปรแกรมเมอร์ C ++ ที่จะทำงานด้วย - วันที่พิมพ์ต่อไปนี้จะเป็นวันที่ดังต่อไปนี้:
#include <ctime>
#include <iostream>
int main() {
    std::time_t t = std::time(0);   // get time now
    std::tm* now = std::localtime(&t);
    std::cout << (now->tm_year + 1900) << '-' 
         << (now->tm_mon + 1) << '-'
         <<  now->tm_mday
         << "\n";
}ctime()ร่วมกับคำตอบนี้หากคุณต้องการสตริงวันที่
                    struct tmมันเป็นไปได้เพียงแค่โทรลบมัน?
                    delete(คำหลัก c ++) กับมันฉันแค่คิดว่ามันควรจะถูกลบอย่างใด :) หรือผู้ที่จะทำเช่นนั้นสำหรับคุณ?
                    คุณสามารถลองใช้รหัสข้ามแพลตฟอร์มต่อไปนี้เพื่อรับวันที่ / เวลาปัจจุบัน:
#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>
// 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 << "currentDateTime()=" << currentDateTime() << std::endl;
    getchar();  // wait for keyboard input
}เอาท์พุท:
currentDateTime()=2012-05-06.21:47:59กรุณาเยี่ยมชม ที่นี่สำหรับข้อมูลเพิ่มเติมเกี่ยวกับรูปแบบวันที่ / เวลา
constค่า มันไม่มีจุดมุ่งหมาย
                    ห้องสมุดมาตรฐาน C time()ให้ นี่คือวินาทีจากยุคและสามารถแปลงเป็นวันที่และH:M:Sใช้ฟังก์ชั่น C มาตรฐาน Boostยังมีไลบรารีเวลา / วันที่ที่คุณสามารถตรวจสอบได้
time_t  timev;
time(&timev);ไลบรารีมาตรฐาน C ++ ไม่ได้ให้ประเภทวันที่ที่เหมาะสม C ++ สืบทอดโครงสร้างและฟังก์ชั่นสำหรับการจัดการวันที่และเวลาจาก C พร้อมกับฟังก์ชั่นอินพุทและเอาท์พุทสองสามวัน / เวลาที่คำนึงถึงการแปลบัญชี
// 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 << "The local date and time is: " << asctime(localtm) << endl;
// Convert now to tm struct for UTC
tm* gmtm = gmtime(&now);
if (gmtm != NULL) {
cout << "The UTC date and time is: " << asctime(gmtm) << endl;
}
else {
cerr << "Failed to get the UTC date and time" << endl;
return EXIT_FAILURE;
}คำตอบใหม่สำหรับคำถามเก่า:
คำถามไม่ได้ระบุในเขตเวลาใด มีความเป็นไปได้ที่สมเหตุสมผลสองประการ:
สำหรับ 1 คุณสามารถใช้ไลบรารีวันที่นี้และโปรแกรมต่อไปนี้:
#include "date.h"
#include <iostream>
int
main()
{
    using namespace date;
    using namespace std::chrono;
    std::cout << system_clock::now() << '\n';
}ซึ่งเพิ่งออกมาสำหรับฉัน:
2015-08-18 22:08:18.944211std::chrono::system_clock::time_pointห้องสมุดวันที่หลักเพียงเพิ่มผู้ประกอบการสตรีมมิ่ง นอกจากนี้ยังเพิ่มฟังก์ชั่นที่ดีอื่น ๆ อีกมากมาย แต่ไม่ได้ใช้ในโปรแกรมอย่างง่ายนี้
ถ้าคุณต้องการที่ 2 (ตามเวลาท้องถิ่น) มีห้องสมุดเขตเวลาที่สร้างขึ้นบนด้านบนของห้องสมุดวัน ทั้งสองไลบรารีนี้เป็นโอเพ่นซอร์สและไขว้แพลตฟอร์มสมมติว่าคอมไพเลอร์รองรับ C ++ 11 หรือ C ++ 14
#include "tz.h"
#include <iostream>
int
main()
{
    using namespace date;
    using namespace std::chrono;
    auto local = make_zoned(current_zone(), system_clock::now());
    std::cout << local << '\n';
}ซึ่งสำหรับฉันเพิ่งออก:
2015-08-18 18:08:18.944211 EDTประเภทผลจากmake_zonedเป็นdate::zoned_timeซึ่งเป็นคู่ของและdate::time_zone std::chrono::system_clock::time_pointคู่นี้แสดงเวลาท้องถิ่น แต่ยังสามารถแทน UTC ได้ขึ้นอยู่กับว่าคุณสืบค้นอย่างไร
ด้วยผลลัพธ์ข้างต้นคุณจะเห็นว่าปัจจุบันคอมพิวเตอร์ของฉันอยู่ในเขตเวลาที่มีเวลาอ็อฟเซ็ต UTC ด้วย -4h และตัวย่อของ EDT
หากต้องการเขตเวลาอื่นที่สามารถทำได้ ตัวอย่างเช่นเพื่อค้นหาเวลาปัจจุบันในซิดนีย์ออสเตรเลียเพียงแค่เปลี่ยนการสร้างตัวแปรlocalเป็น:
auto local = make_zoned("Australia/Sydney", system_clock::now());และผลลัพธ์จะเปลี่ยนเป็น:
2015-08-19 08:08:18.944211 AESTขณะนี้ไลบรารีนี้ได้รับการรับรองสำหรับ C ++ 20 เป็นส่วนใหญ่ namespace dateหายไปและทุกอย่างอยู่ใน namespace std::chronoทันที และใช้ในสถานที่ของzoned_time make_timeวางส่วนหัว"date.h"และและการใช้งานเพียงแค่"tz.h"<chrono>
ขณะที่ฉันเขียนสิ่งนี้การใช้งานบางส่วนเพิ่งจะเริ่มปรากฏขึ้นในบางแพลตฟอร์ม
localtimeให้เวลากับฉันในเขตเวลาของฉัน?
                    localtimeจะเกือบเสมอให้คุณมีเวลาในเขตเวลาท้องถิ่นของคุณเพื่อความแม่นยำที่สอง บางครั้งมันจะล้มเหลวเนื่องจากปัญหา threadsafety และมันจะไม่ทำงานเพื่อความแม่นยำรอง
                    (สำหรับเพื่อนชาว Google)
นอกจากนี้ยังมีBoost :: date_time :
#include <boost/date_time/posix_time/posix_time.hpp>
boost::posix_time::ptime date_time = boost::posix_time::microsec_clock::universal_time();auto time = std::time(nullptr);
std::cout << std::put_time(std::localtime(&time), "%F %T%z"); // ISO 8601 format.รับเวลาปัจจุบันไม่ว่าจะใช้std::time()หรือstd::chrono::system_clock::now()(หรือประเภทนาฬิกาอื่น)
std::put_time()(C ++ 11) และstrftime()(C) เสนอตัวจัดรูปแบบจำนวนมากเพื่อส่งออกเวลาเหล่านั้น
#include <iomanip>
#include <iostream>
int main() {
    auto time = std::time(nullptr);
    std::cout
        // ISO 8601: %Y-%m-%d %H:%M:%S, e.g. 2017-07-31 00:42:00+0200.
        << std::put_time(std::gmtime(&time), "%F %T%z") << '\n'
        // %m/%d/%y, e.g. 07/31/17
        << std::put_time(std::gmtime(&time), "%D"); 
}ลำดับของ formatters สำคัญ:
std::cout << std::put_time(std::gmtime(&time), "%c %A %Z") << std::endl;
// Mon Jul 31 00:00:42 2017 Monday GMT
std::cout << std::put_time(std::gmtime(&time), "%Z %c %A") << std::endl;
// GMT Mon Jul 31 00:00:42 2017 Mondayตัวจัดรูปแบบของstrftime()มีความคล้ายคลึงกัน:
char output[100];
if (std::strftime(output, sizeof(output), "%F", std::gmtime(&time))) {
    std::cout << output << '\n'; // %Y-%m-%d, e.g. 2017-07-31
}บ่อยครั้งที่ตัวจัดรูปแบบทุนหมายถึง "เวอร์ชันเต็ม" และตัวพิมพ์เล็กหมายถึงตัวย่อ (เช่น Y: 2017, y: 17)
การตั้งค่าตำแหน่งกระทำการเปลี่ยนผลลัพธ์:
#include <iomanip>
#include <iostream>
int main() {
    auto time = std::time(nullptr);
    std::cout << "undef: " << std::put_time(std::gmtime(&time), "%c") << '\n';
    std::cout.imbue(std::locale("en_US.utf8"));
    std::cout << "en_US: " << std::put_time(std::gmtime(&time), "%c") << '\n';
    std::cout.imbue(std::locale("en_GB.utf8"));
    std::cout << "en_GB: " << std::put_time(std::gmtime(&time), "%c") << '\n';
    std::cout.imbue(std::locale("de_DE.utf8"));
    std::cout << "de_DE: " << std::put_time(std::gmtime(&time), "%c") << '\n';
    std::cout.imbue(std::locale("ja_JP.utf8"));
    std::cout << "ja_JP: " << std::put_time(std::gmtime(&time), "%c") << '\n';
    std::cout.imbue(std::locale("ru_RU.utf8"));
    std::cout << "ru_RU: " << std::put_time(std::gmtime(&time), "%c");        
}เอาต์พุตที่เป็นไปได้ ( Coliru , Compiler Explorer ):
undef: Tue Aug  1 08:29:30 2017
en_US: Tue 01 Aug 2017 08:29:30 AM GMT
en_GB: Tue 01 Aug 2017 08:29:30 GMT
de_DE: Di 01 Aug 2017 08:29:30 GMT
ja_JP: 2017年08月01日 08時29分30秒
ru_RU: Вт 01 авг 2017 08:29:30ฉันใช้std::gmtime()สำหรับการแปลงเป็น UTC std::localtime()มีไว้เพื่อแปลงเป็นเวลาท้องถิ่น
สังเกตว่าasctime()/ ctime()ซึ่งถูกกล่าวถึงในคำตอบอื่น ๆ ถูกทำเครื่องหมายว่าเลิกใช้แล้วและstrftime()ควรเป็นที่ต้องการ
#include <stdio.h>
#include <time.h>
int main ()
{
  time_t rawtime;
  struct tm * timeinfo;
  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  printf ( "Current local time and date: %s", asctime (timeinfo) );
  return 0;
} ใช่และคุณสามารถทำได้โดยใช้กฎการจัดรูปแบบที่ระบุโดยสถานที่ที่มีอยู่ในปัจจุบัน:
#include <iostream>
#include <iterator>
#include <string>
class timefmt
{
public:
    timefmt(std::string fmt)
        : format(fmt) { }
    friend std::ostream& operator <<(std::ostream &, timefmt const &);
private:
    std::string format;
};
std::ostream& operator <<(std::ostream& os, timefmt const& mt)
{
    std::ostream::sentry s(os);
    if (s)
    {
        std::time_t t = std::time(0);
        std::tm const* tm = std::localtime(&t);
        std::ostreambuf_iterator<char> out(os);
        std::use_facet<std::time_put<char>>(os.getloc())
            .put(out, os, os.fill(),
                 tm, &mt.format[0], &mt.format[0] + mt.format.size());
    }
    os.width(0);
    return os;
}
int main()
{
    std::cout << timefmt("%c");
}เอาท์พุท:
Fri Sep 6 20:33:31 2013
ostream::sentryบ่อยครั้ง)
                    คุณสามารถใช้คลาส C ++ 11:
    #include <iostream>
    #include <iomanip>
    using namespace std;
    int main() {
       time_t now = chrono::system_clock::to_time_t(chrono::system_clock::now());
       cout << put_time(localtime(&now), "%F %T") <<  endl;
      return 0;
     }ใส่ออก:
2017-08-25 12:30:08มี__TIMESTAMP__มาโครตัวประมวลผลล่วงหน้าเสมอ
#include <iostream>
using namespace std
void printBuildDateTime () {
    cout << __TIMESTAMP__ << endl;
}
int main() {
    printBuildDateTime();
}ตัวอย่าง: อา. 13 เม.ย. 11:28:08 น
__TIMESTAMP__เป็นแมโครตัวประมวลผลล่วงหน้าที่ขยายเวลาปัจจุบัน (ณ เวลารวบรวม) ในรูปแบบ Ddd Mmm Date hh :: mm :: ss yyyy __TIMESTAMP__แมโครสามารถใช้ในการให้ข้อมูลเกี่ยวกับช่วงเวลาโดยเฉพาะอย่างยิ่งไบนารีที่ถูกสร้างขึ้น อ้างอิง: cprogramming.com/reference/preprocessor/__TIMESTAMP__.html
                    คุณยังสามารถใช้โดยตรงctime():
#include <stdio.h>
#include <time.h>
int main ()
{
  time_t rawtime;
  struct tm * timeinfo;
  time ( &rawtime );
  printf ( "Current local time and date: %s", ctime (&rawtime) );
  return 0;
} #define _CRT_SECURE_NO_DEPRECATEก่อนรวมเพื่อให้คอมไพล์โปรแกรม
                    ฉันพบลิงค์นี้ค่อนข้างมีประโยชน์สำหรับการใช้งานของฉัน: C ++ วันและเวลา
นี่คือรหัสที่ฉันใช้ในการติดตั้งเพื่อรับรูปแบบเอาต์พุต "YYYYMMDD HHMMSS" ที่ชัดเจน พารามิเตอร์ในสำหรับการสลับระหว่าง UTC และเวลาท้องถิ่น คุณสามารถแก้ไขรหัสของฉันได้อย่างง่ายดายเพื่อให้ตรงกับความต้องการของคุณ
#include <iostream>
#include <ctime>
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 << 1900 + ptmNow->tm_year;
    //month
    if (ptmNow->tm_mon < 9)
        //Fill in the leading 0 if less than 10
        currentDateTime << "0" << 1 + ptmNow->tm_mon;
    else
        currentDateTime << (1 + ptmNow->tm_mon);
    //day
    if (ptmNow->tm_mday < 10)
        currentDateTime << "0" << ptmNow->tm_mday << " ";
    else
        currentDateTime <<  ptmNow->tm_mday << " ";
    //hour
    if (ptmNow->tm_hour < 10)
        currentDateTime << "0" << ptmNow->tm_hour;
    else
        currentDateTime << ptmNow->tm_hour;
    //min
    if (ptmNow->tm_min < 10)
        currentDateTime << "0" << ptmNow->tm_min;
    else
        currentDateTime << ptmNow->tm_min;
    //sec
    if (ptmNow->tm_sec < 10)
        currentDateTime << "0" << ptmNow->tm_sec;
    else
        currentDateTime << ptmNow->tm_sec;
    return currentDateTime.str();
}เอาท์พุท (UTC, EST):
20161123 000454
20161122 190454ptmNow->tm_day < 9ไม่<10?
                    <=9เพราะคุณต้องการรวม 9 หรือไม่
                    1+รหัส วัน / เดือนเริ่มต้นที่ 0.
                    สิ่งนี้ใช้ได้กับ G ++ ฉันไม่แน่ใจว่าสิ่งนี้จะช่วยคุณได้หรือไม่ ผลลัพธ์ของโปรแกรม:
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.รหัส:
#include <ctime>
#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>
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 << "\033[2J\033[1;1H"; 
std:cout << "The current time is " << currentTime() << std::endl;
    time_t t = time(0);   // get time now
    struct tm * now = localtime( & t );
    cout << "The current date is " << now->tm_mon + 1 << '-' 
         << (now->tm_mday  + 1) << '-'
         <<  (now->tm_year + 1900) 
         << " " << currentDate() << endl; 
 cout << "Day of month is " << (now->tm_mday) 
      << " and the Month of year is " << (now->tm_mon)+1 << "," << endl;
    cout << "also the day of year is " << (now->tm_yday) 
         << " & our Weekday is " << (now->tm_wday) << "." << endl;
    cout << "The current year is " << (now->tm_year)+1900 << "." 
         << endl;
 return 0;  
}สิ่งนี้ได้รวบรวมสำหรับฉันบน Linux (RHEL) และ Windows (x64) การกำหนดเป้าหมาย g ++ และ OpenMP:
#include <ctime>
#include <iostream>
#include <string>
#include <locale>
////////////////////////////////////////////////////////////////////////////////
//
//  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 << strName << ": " << strUpdate << ": " << (1900 + tmStart.tm_year) << "-" << tmStart.tm_mon << "-" << tmStart.tm_mday << " " << tmStart.tm_hour << ":" << tmStart.tm_min << ":" << tmStart.tm_sec << "\n\n";
        #else
            //  Current time
            const time_t tStart = time(0);
            //  Current time structure
            struct tm* tmStart;
            tmStart = localtime(&tStart);
            //  Report
            cout << strName << ": " << strUpdate << ": " << (1900 + tmStart->tm_year) << "-" << tmStart->tm_mon << "-" << tmStart->tm_mday << " " << tmStart->tm_hour << ":" << tmStart->tm_min << ":" << tmStart->tm_sec << "\n\n";
        #endif
    }
    catch (exception ex)
    {
        cout << "ERROR [ReportTimeStamp] Exception Code:  " << ex.what() << "\n";
    }
    return;
}คุณสามารถใช้รหัสต่อไปนี้เพื่อรับวันที่และเวลาของระบบปัจจุบันในC ++ :
    #include <iostream>
    #include <time.h> //It may be #include <ctime> 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 << "The local date and time is: " << dt << endl;
    return 0;
    }PS: เยี่ยมชมเว็บไซต์นี้สำหรับข้อมูลเพิ่มเติม
ffead-CPPให้อาคารเรียนหลายงานต่างๆหนึ่งชั้นเรียนดังกล่าวเป็นวันที่ระดับซึ่งมีจำนวนมากที่มีคุณสมบัติที่เหมาะสมจากการดำเนินงานวันที่จะคำนวณวันที่นอกจากนี้ยังมีตัวจับเวลาชั้นที่จัดไว้ให้สำหรับการดำเนินงานระยะเวลา คุณสามารถดูได้เหมือนกัน
http://www.cplusplus.com/reference/ctime/strftime/
ดูเหมือนว่าในตัวจะมีตัวเลือกที่เหมาะสม
time_t rawTime;     time(&rawTime);     struct tm *timeInfo;     char buf[80];     timeInfo = localtime(&rawTime);     strftime(buf, 80, "%T", timeInfo);  นี้ใส่ HH: MM: SS โพสต์แรกของฉันดังนั้นฉันไม่แน่ใจว่าจะแก้ไขรูปแบบรหัสได้อย่างไร ขอโทษด้วยกับเรื่องนั้น.
                    localtime_s () เวอร์ชัน:
#include <stdio.h>
#include <time.h>
int main ()
{
  time_t current_time;
  struct tm  local_time;
  time ( ¤t_time );
  localtime_s(&local_time, ¤t_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;
} #include <iostream>
#include <chrono>
#include <string>
#pragma warning(disable: 4996)
// Ver: C++ 17 
// IDE: Visual Studio
int main() {
    using namespace std; 
    using namespace chrono;
    time_point tp = system_clock::now();
    time_t tt = system_clock::to_time_t(tp);
    cout << "Current time: " << ctime(&tt) << endl;
    return 0;
}#include <Windows.h>
void main()
{
     //Following is a structure to store date / time
SYSTEMTIME SystemTime, LocalTime;
    //To get the local time
int loctime = GetLocalTime(&LocalTime);
    //To get the system time
int systime = GetSystemTime(&SystemTime)
}void mainไม่ได้เป็น C / C ++ มาตรฐาน
                    คุณสามารถใช้boost:
#include <boost/date_time/gregorian/gregorian.hpp>
#include <iostream>
using namespace boost::gregorian;
int main()
{
    date d = day_clock::universal_day();
    std::cout << d.day() << " " << d.month() << " " << d.year();
}