How to convert time in seconds to Years, Months, Weeks, Days, Hours etc…

29 12 2012

There are several different formats used in different places to represent time. Recently I met with a problem that in one of my applications, it was getting time in seconds and the requirement was to calculate how many Years, Moths, Weeks, Days, Hours, Minutes and Seconds in that.

A small algorithm with division (/) and modulo (%) operator makes us to do it easily.

const int DAYS_IN_YEAR = 365;
const int DAYS_IN_MONTH = 30; //consider 30 Days
const int DAYS_IN_WEEK = 7;
const int HOURS_IN_DAY = 24;
const int MINS_IN_HOUR = 60;
const int SECS_IN_MIN = 60;

CString ConvertTime(long nInputInSeconds)
{
	int nYears   = 0;
	int nMonths  = 0;
	int nWeeks   = 0;
	int nDays    = 0;
	int nHours   = 0;
	int nMinutes = 0;
	int nSeconds = 0;

	const int nSecondsInOneYear = SECS_IN_MIN * MINS_IN_HOUR * HOURS_IN_DAY * DAYS_IN_YEAR;
	const int nSecondsInOneMonth = SECS_IN_MIN * MINS_IN_HOUR * HOURS_IN_DAY * DAYS_IN_MONTH;
	const int nSecondsInOneWeek = SECS_IN_MIN * MINS_IN_HOUR * HOURS_IN_DAY * DAYS_IN_WEEK;
	const int nSecondsInOneDay = SECS_IN_MIN * MINS_IN_HOUR * HOURS_IN_DAY;
	const int nSecondsInOneHour = SECS_IN_MIN * MINS_IN_HOUR;

	nYears = nInputInSeconds / nSecondsInOneYear;
	nMonths = (nInputInSeconds % nSecondsInOneYear) / nSecondsInOneMonth;
	nWeeks = ((nInputInSeconds % nSecondsInOneYear) % nSecondsInOneMonth ) / nSecondsInOneWeek;
	nDays = (((nInputInSeconds % nSecondsInOneYear) % nSecondsInOneMonth ) % nSecondsInOneWeek) / nSecondsInOneDay;
	nHours = ((((nInputInSeconds % nSecondsInOneYear) % nSecondsInOneMonth ) % nSecondsInOneWeek) % nSecondsInOneDay) / nSecondsInOneHour;
	nMinutes = (((((nInputInSeconds % nSecondsInOneYear) % nSecondsInOneMonth ) % nSecondsInOneWeek) % nSecondsInOneDay) % nSecondsInOneHour) / SECS_IN_MIN;
	nSeconds = ((((((nInputInSeconds % nSecondsInOneYear) % nSecondsInOneMonth ) % nSecondsInOneWeek) % nSecondsInOneDay) % nSecondsInOneHour) % SECS_IN_MIN);

	CString str;
	str.Format(_T("%d Years, %d Months, %d Weeks, %d Days, %d Hours, %d Minutes, %d Seconds"),
		nYears, nMonths, nWeeks, nDays, nHours, nMinutes, nSeconds);
	return str;
}

You may get some minor differences as it always considers exactly 30 days in each months.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: