Split down a number in seconds to days, hours, minutes, and seconds?

前端 未结 3 998
天涯浪人
天涯浪人 2021-02-02 17:06

I\'ve heard that it\'s possible to accomplish this using the modulus % operator present in most programming languages. The real question is, how? I\'m unfamiliar wi

3条回答
  •  星月不相逢
    2021-02-02 17:45

    Whenever converting from a small base unit (seconds) to a series of larger units (minutes/hours/days/years/decades/centuries/millennia) you can use the modulo (%) operator to keep track of the remaining base units as you extract each large unit.

    It is an elegant/simple way to keep a sort of running total in base units. Start extracting BaseUnits with the largest unit you want and work your way back down until you get to the original BaseUnit.

    This only works when the extracted unit is nonzero. If it's zero then you have extracted no base units at all and don't need the modulo operator.

    It is important to remember that the result of the modulo operation will always be in the original base unit. That can get confusing.

    Let's restate 1 million seconds as larger time units. Let 1 year = 31,536,000 seconds and no leap years or other calendar adjustments.

    #include 
    #define SEC2CENT 3153600000
    #define SEC2DEC 315360000
    #define SEC2YR 31536000
    #define SEC2MONTH 2592000
    #define SEC2WEEK 604800
    #define SEC2DAY 86400
    #define SEC2HOUR 3600
    #define SEC2MIN 60
    main()
    {
    unsigned int sec = 1000000; //I am 1 million seconds old or...
    
    unsigned int centuries = sec / SEC2CENT;
    if (centuries) sec = sec % SEC2CENT; //if nonzero update sec
    
    unsigned int decades = sec / SEC2DEC;
    if (decades) sec = sec % SEC2DEC; //the purpose of modulo for units is this running total of base units
    
    unsigned int years = sec / SEC2YR;
    if (years) sec = sec % SEC2YR;
    
    unsigned int months = sec / SEC2MONTH;
    if (months) sec = sec % SEC2MONTH;
    
    unsigned int weeks = sec / SEC2WEEK;
    if (weeks) sec = sec % SEC2WEEK;
    
    unsigned int days = sec / SEC2DAY;
    if (days) sec = sec % SEC2DAY;
    
    unsigned int hours = sec / SEC2HOUR;
    if (hours) sec = sec % SEC2HOUR;
    
    unsigned int minutes = sec / SEC2MIN;
    if (minutes) sec = sec % SEC2MIN;
    
    unsigned int seconds = sec; //seconds should now be less than 60 because of minutes
    
    printf("I am now exactly %u centuries, %u decades, %u years, %u months, %u weeks, %u days, %u hours, %u minutes, %u seconds old and that is very old indeed.", centuries, decades, years, months, weeks, days, hours, minutes, seconds);
    }
    

提交回复
热议问题