October 15, 2018 by Reion

Percentage of year passed

Last night in the App Store, I saw an app that provides a widget to show how much percentage of the year has passed, it reminds you to value your time, every 52 minutes, the percentage will increase by 0.01%, it costs CNY 3 to buy it and i paid to experience it directly.

border|inline

The calculation algorithm is as follows:

There are 24 hours in a day, 60 minutes in an hour, and 60 seconds in a minute.

Therefore, there are 86,400 seconds in a day.

The total number of seconds in a year is calculated by multiplying the total number of days in a year by 24, 60, and 60. Like: total_number * 24 * 60 * 60 is total_number_of_seconds_in_year.

So, the final calculation can be done using this formula:

(Number of seconds elapsed in a year / Total number of seconds in a year) * 100.0

C++ code

#include <iostream>
#include <ctime>

int main(int argc, char *argv[])
{
    time_t now = time(0);
    tm *ltm = localtime(&now);
    int year = 1900 + ltm->tm_year;
    int total_days = 0;

    // 公历是 4 的倍数就是闰年,例如 2010 除以 4,不是整数倍,所以 2010 年是平年.
    if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
        total_days = 366;
    } else {
        total_days = 365;
    }

    long total_seconds = total_days * 24 * 60 * 60;

    // 年初时间
    struct tm year_time;
    year_time.tm_hour = 00;
    year_time.tm_min = 00;
    year_time.tm_sec = 00;
    year_time.tm_mday = 01;
    year_time.tm_mon = 1-1;
    year_time.tm_year = ltm->tm_year;

    // 算出今年年初到现在的秒数
    double now_seconds = difftime(mktime(ltm), mktime(&year_time));
    double percent = (double)now_seconds / (double)total_seconds * 100.0;
    std::cout << percent << std::endl;

    return 0;
}