小さな基本単位(秒)から一連の大きな単位(分/時間/日/年/数十年/世紀/千年)に変換するときはいつでも、モジュロ(%)演算子を使用して、残りの基本単位を追跡できます。各大きなユニットを抽出します。
これは、ある種の現在の合計を基本単位で維持するためのエレガントでシンプルな方法です。必要な最大のユニットでBaseUnitの抽出を開始し、元のBaseUnitに到達するまで下に戻ります。
これは、抽出された単位がゼロ以外の場合にのみ機能します。ゼロの場合、基本単位はまったく抽出されておらず、モジュロ演算子は必要ありません。
モジュロ演算の結果は常に元の基本単位になることを覚えておくことが重要です。それは混乱する可能性があります。
100万秒をより大きな時間単位として言い換えましょう。1年=31,536,000秒とし、うるう年やその他のカレンダー調整は行いません。
#include <cstdio>
#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);
}