Erlang Thursday – calendar:day_of_the_week/3

今天的Erlang Thursday讲的是 calendar:day_of_the_week/3.

calendar:day_of_the_week/3 允许你传入年、月、日然后得到这个日子在一个星期里是第几天。

第一个入参表示年份而且必须是非负整数。第二个入参是月份而且必须是1到12的整数(包括1和12),它表示公历的12个月份,1表示1月份。最后一个入参是第几日,必须是1到31(包括1和31)的整数。

calendar:day_of_the_week/3 返回一个1到7(包括1和7)的整数值,1表示星期一,7表示星期日。

1
2
3
4
5
6
7
8
calendar:day_of_the_week(1, 1, 1).
% 1
calendar:day_of_the_week(1970, 1, 1).
% 4
calendar:day_of_the_week(1999, 12, 31).
% 5
calendar:day_of_the_week(0, 1, 1).
% 6

本篇文章的发布日期是2015年4月9日,把它传给 calendar:day_of_the_week/3 ,得到返回值是4,正好表示星期四,也就是本系列文章发布的日子。

1
2
calendar:day_of_the_week(2015, 4, 9).
% 4

还有一个 calendar:day_of_the_week/1 函数,它和上面的函数功能和参数要求基本一样,只是它只接收一个入参,这个入参是由年、月、日组成的三元素元组。

1
2
3
4
5
6
calendar:day_of_the_week({2015, 4, 9}).
% 4
calendar:day_of_the_week({1970, 1, 1}).
% 4
calendar:day_of_the_week({1999, 12, 31}).
% 5

为了帮助大家认识 calendar:day_of_the_week/3 函数返回的错误消息,让我们看看,当我们给该函数传递无效日期,我们会得到什么。

1
2
3
4
5
6
7
8
9
10
11
calendar:day_of_the_week(0, 0, 0).
% ** exception error: no function clause matching calendar:date_to_gregorian_days(0,0,0) (calendar.erl, line 114)
% in function calendar:day_of_the_week/3 (calendar.erl, line 151)
calendar:day_of_the_week(1970, 2, 31).
% ** exception error: no true branch found when evaluating an if expression
% in function calendar:date_to_gregorian_days/3 (calendar.erl, line 116)
% in call from calendar:day_of_the_week/3 (calendar.erl, line 151)
calendar:day_of_the_week(1970, 13, 2).
% ** exception error: no function clause matching calendar:last_day_of_the_month1(1970,13) (calendar.erl, line 243)
% in function calendar:date_to_gregorian_days/3 (calendar.erl, line 115)
% in call from calendar:day_of_the_week/3 (calendar.erl, line 151)

如果你仔细看这些错误消息,你会看到 calendar:day_of_the_week/3 调用了 calendar:date_to_gregorian_days/3 ,我们将在下个星期的Erlang Thursday来介绍它。

原文链接: https://www.proctor-it.com/erlang-thursday-calendar-day_of_the_week-3/