如何获取当前系统时间并转换为数组?

How to get current system time and cast in array?

我想分别获取时间和日期放到一个数组中。我希望调用函数类似于 int date(int Day,int Month,int Year) 但它不正确。如何定义函数的参数年月日和时分秒以使用它们?

using namespace std;
int date() {
    time_t currentTime;
    struct tm *localTime;

    time(&currentTime);                  
    localTime = localtime(&currentTime);

     int Day = localTime->tm_mday;
     int Month = localTime->tm_mon + 1;
     int Year = localTime->tm_year + 1900;
    return (0);
}
int time() {
    time_t currentTime;
    struct tm *localTime;

    time(&currentTime);                   
    localTime = localtime(&currentTime); 

    int Hour = localTime->tm_hour;
    int Min = localTime->tm_min;
    int Sec = localTime->tm_sec;
    return (0);
}
int main() {
    unsigned int new_date=date();
    char write[4];
    memcpy(write,&new_date,4);

    unsigned int new_time=time();
       char wrt[4];
       memcpy(wrt,&new_time,4);



    }

您必须声明通过引用传递参数的函数:

              // pass arguments by reference to change them in the function 
int date(int &Day, int &Month, int&Year) {
    time_t currentTime;
    struct tm *localTime;

    time(&currentTime);                  
    localTime = localtime(&currentTime);

     Day = localTime->tm_mday;   // use the reference argument
     Month = localTime->tm_mon + 1;
     Year = localTime->tm_year + 1900;

    return (0);
}

然后您可以在 main() 中像这样使用它:

int d,m,y; 
date(d,m,y); 
cout << d<<"/"<<m<<"/"<<y<<endl;

你当然可以对时间做同样的事情。