计算SAS中一个月的天数

时间:2017-12-05 20:39:06

标签: sql sas

我希望在SAS中获得一个月的天数。我的日期格式是yyyymm(例如201701),我想记录一个月的天数。数据每月重复(201701,201702 ......等)。我尝试使用Day功能和EOMONTH,但是SAS选择了201701的SAS日期。我是SAS编码的新手,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

SAS日期值是数字类型,其值是自1960年1月1日以来的天数。

您需要先了解代表变量的日期的值类型。 是吗:

  • 在含义位置使用数字字母的字符类型Y Y Y Y M M
  • 数字类型,日期编码为值100 *年+月

如果EOMONTH是字符,则需要将其转换为包含一天的SAS日期值。对于'月'当天的值通常设置为1.例如:

data _null_;
  myDateString = '201701';
  * note the ||'01' that makes myDate be the first of the month;
  myDate = input (trim(myDateString)||'01', yymmdd8.);
  format myDate yymmd.;
  put myDate=;
  put myDate= 12.; * Show in LOG the date as number of days from reference;
run;
----- LOG -----
myDate=2017-01
myDate=20820

有时,您将获得表示数字和编码的数据的日期,以便在查看时显示为YYYYMM。这些值也需要转换为SAS日期值。例如:

data have;
  myDateNumber = 201701;
  * note the , 1 that makes myDate be the first of the month;
  myDate = mdy ( mod(myDateNumber,100), 1, myDateNumber / 100);
  format myDate yymmd.;
  put myDate=;
  put myDate= 12.; * What date value is 'unformatted' is the number of days from reference;
run;
----- LOG -----
myDate=2017-01
myDate=20820

还有其他方法可以将日期的字符或数字表示转换为SAS日期值。请注意,当您在SAS中查看变量时,您需要知道变量类型和查看器应用的格式。

获得SAS日期值后,您可以使用SAS间隔函数INTCK和INTNX计算该日期当月的天数。

days_in_month = intck ('days', /* how many days between next two args */
  intnx('month', mydate, 0),  /* advance mydate to first of month */
  intnx('month', mydate, 1)   /* advance mydate to first of next month */
);

此公式无论日期值的月份日期都有效。

相关问题