C语言根据日期取其位于一年中的第几天

#include <iostream>
#include <stdlib.h>

using namespace std;

bool isLeapYear( int iYear )
{//判断闰年
	if( iYear < 0 )
		return false;
	
	if( !(iYear % 400) )
		return true;

	if( !( iYear % 100 ))
		return false;

	if( !( iYear % 4 ) )
		return true;

	return false;
}

int GetDayInYear( int iYear, int iMonth, int iDay )
{//成功则返回1-366中的一个数失败则返回-1
	if( iYear < 0 )
		return -1;

	if( iMonth > 13 || iMonth < 1 )
		return -1;

	const int leapYear[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	const int noLeapYear[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

	int i;
	int iCurMonth = iMonth - 1;
	int iIndex = 0;
	if( isLeapYear( iYear ) )
	{//闰年
		for( i = 0; i < iCurMonth; i++ )
		{
			iIndex += leapYear[i];
		}

		if( iDay > leapYear[i] || iDay < 1 )
			return -1;

		iIndex += iDay;
	}
	else
	{
		for( i = 0; i < iCurMonth; i++ )
		{
			iIndex += noLeapYear[i];
		}

		if( iDay > noLeapYear[i] || iDay < 1 )
			return -1;

		iIndex += iDay;
	}

	return iIndex;
}

int main( int argc, char* argv[] )
{
	printf( "Day in Year: %d\n" ,GetDayInYear( 2000, 2, 30 ) );

	return 0;
}


posted @ 2013-08-04 20:43  javawebsoa  Views(291)  Comments(0Edit  收藏  举报