Erlang implements the number of days between two dates

-module(demo).
-export([date/6, isleapyear/1, sumday/3, frontday/5, backday/5]).

date(Year1, Month1, Day1, Year2, Month2, Day2) -> 
	L1 = [31,29,31,30,31,30,31,31,30,31,30,31],
	L2 = [31,28,31,30,31,30,31,31,30,31,30,31],
	case [Year1, Year2] of
		_ when Year1 =:= Year2 -> frontday(Year2, Month2, Day2, L1, L2) - frontday(Year1, Month1, Day1, L1, L2); %judge  Year1 == Year2 
		_Other -> sumday(Year1, Year2, 0) + backday(Year1, Month1, Day1, L1, L2) + frontday(Year2, Month2, Day2, L1, L2)
	end.



isleapyear(Year) ->     % judge if a year is leap year
	case Year of
		_ when  Year rem 400 =:= 0; Year rem 100 =/= 0, Year rem 4 == 0 -> true;
		_Other -> false
	end.


sumday(Year1, Year2, Sum)->  % cauculate the days between Year1, Year2 , eg. 2012, 2014  365.
	case [Year1, Year2] of
		_ when Year1 + 1 =:= Year2 -> Sum;
		_->
			case isleapyear(Year1 + 1) of
				true -> sumday(Year1 + 1, Year2, Sum + 366);
				false -> sumday(Year1 + 1, Year2, Sum + 365)
			end
	end.			


frontday(Year, Month, Day, L1, L2) -> %cauculate how many days have passed of a date in this year 
	case isleapyear(Year) of
		true -> lists:sum(lists:sublist(L1, Month - 1)) + Day;
		false -> lists:sum(lists:sublist(L2, Month - 1)) + Day 
	end.

backday(Year, Month, Day, L1, L2) -> %cauculate how many days left of a date in this year 
	case isleapyear(Year) of
		true -> 366 - frontday(Year, Month, Day, L1, L2);
		false -> 365 - frontday(Year, Month, Day ,L1, L2)
	end.

  Recently studying erlang, I did a test and recorded it.

Guess you like

Origin www.cnblogs.com/icehole/p/12705447.html