C++ 如何从一个整数值中获取三个单独的日期值(日、月、年)

C++ How to Get three separate date values (day, month, year) from one integer value

本文关键字:日期 单独 三个 一个 整数 C++ 获取      更新时间:2023-10-16

好吧,我要求用户输入 (yyyy/mm/dd) 格式的日期,然后在这种情况下它下降到一个函数 dateSplit。我明白我怎么能一年,因为我知道它总是我可以模数的前四位数字。任何人都知道一种方法来做月份,这里的一天是我到目前为止的代码:

void dateSplit(int date, int& year, int& day, int& mon)
{
    // date % 10000 is a floating point value but i put it into an int to cut the back off
    date % 10000 = year;
}

有谁明白我怎么能只读中间的两个数字和最后两个数字?

我想我会把我的主要代码放在这里,以便人们可以看到整个画面:

int main()
{
    // Variable Declarations
    string airportCode, lat, longitude, timeZone;
    int date;
    char contin = 'Y';
    while (contin == 'Y' || contin == 'y')
    {
        // Ask User for Airport Code
        cout << "Please Enter an Airport Code: ";
        cin >> airportCode;
        //Call to retrieve information
        retrieveFromFile(airportCode, lat, longitude, timeZone);
        //Call for date
        cout << endl << "Please Enter a date(yyyy/mm/dd): ";
        cin >> date;
        // Continue running program?
        cout << endl << "Would you like to continue? (Y/N): ";
        cin >> contin;
    }
}

这是最终做到的代码:

     void dateSplit(int date, int& year, int& day, int& mon)
    {
        // Ex. if date is 20150623, then it takes that number
        // moves the decimal place over four digits
        // then cuts off after the decimal point
        // leaving just the first four digits
        year = date / 10000;
        date %= 10000;
        mon = date / 100;
        day = date % 100;


        cout << endl << "Year: " << year
             << endl << "Day : " << day
             << endl << "Month:" << mon;
    }

只需使用除法和模数将其切碎,如下所示:

year = date % 10000;
date /= 10000;
month = date % 100;
day = date / 100;