獲得本月最後一天

2021-04-21 14:00:54 字數 2509 閱讀 5408

獲得本月最後一天在abap裡還是非常方便的,大概分的話有兩種方法,一是自己算,而是呼叫系統函式。兩個我都分別演示下。

1.自己運算

date+6(2) = '1'.

date+4(2) = date+4(2) + 1.

date = date - 1.

這個自己寫的有個缺陷,如果為12月的話月份加一全部都變為0.所以還得新增判斷的情況,修改後如下:

date+6(2) = '1'.

if date+4(2) eq '12'.

date+6(2) = '31'.

else.

date+4(2) = date+4(2) + 1.

date = date - 1.

endif.

2.呼叫系統函式

系統函式有兩個函式,讓我感覺奇怪的是居然有乙個是有錯誤的!

錯誤的乙個函式名是date_get_month_lastday。它的具體實現我看了下果然是不對的,如下:

data:

begin

of ls_date,

year(4)  type n,

month(2) type n,

day(2)   type n,

endof ls_date.

data: l_date_tmp type sy-datum.

ls_date = i_date.

ls_date-month = ls_date-month + 1.

ls_date-day   = 1.

l_date_tmp = ls_date.

* no special "leap year" algorithm necessary: in sap nw we trust...

l_date_tmp = l_date_tmp - 1.

e_date = l_date_tmp.

它程式可讀性還是挺高的,用了乙個結構體來表示年月日。但是如果是12月的話結果就會錯,跟我上面自己寫的程式一樣。

正確的乙個系統呼叫程式名是:bkk_get_month_lastday。

實現是:

data: check_year_1 type p.

data: check_year_2 type p.

e_date(4) = i_date(4).

e_date+4(2) = i_date+4(2).

if i_date+4(2) = '01'

or i_date+4(2) = '03'

or i_date+4(2) = '05'

or i_date+4(2) = '07'

or i_date+4(2) = '08'

or i_date+4(2) = '10'

or i_date+4(2) = '12'.

e_date+6(2) = '31'.                " 31 days per month

elseif i_date+4(2) = '04'

or     i_date+4(2) = '06'

or     i_date+4(2) = '09'

or     i_date+4(2) = '11'.

e_date+6(2) = '30'.                " 30 days per month

elseif i_date+4(2) = '02'.           " leap year - problem

e_date+6(2) = '28'.

check_year_1 = i_date(4) mod

4.    " all 4 years is leap year

if check_year_1 = 0.

e_date+6(2) = '29'.

check_year_1 = i_date(4) mod

100." but not all 100 years

check_year_2 = i_date(4) mod

400." excluding all 400 years

if    check_year_1 =  0

and check_year_2 <> 0.

e_date+6(2) = '28'.

endif.

endif.

endif.

又發現了乙個新的函式rp_last_day_of_months 同樣獲得本月最後一天。

concatenate pa_year pa_month '01'

into gv_time.

call

function

'rp_last_day_of_months'

exporting

day_in            = gv_time

importing

last_day_of_month = gv_date_last

exceptions

day_in_no_date    = 1

others            = 2.

sql獲得本週,本月,本年第一天最後一天

本週的第一天 select dateadd wk,datediff wk,0,getdate 0 本年的第一天 select dateadd yy,datediff yy,0,getdate 0 本季度的第一天 select dateadd qq,datediff qq,0,getdate 0 當天...

日期獲取本月第一天和最後一天

getfullyear 日期物件獲取年份 yyyy getmonth 獲取月份0 11 getdate 獲取一月中的第幾天 1 31 setdate num 傳數字設定本月日期第幾天 newdate year month,day,hours,可以傳字串或數字 newdate fullyear,mon...

獲取本月的第一天和最後一天

獲取本月的第一天和最後一天 var firstdate new date firstdate.setdate 1 第一天var enddate new date firstdate enddate.setmonth firstdate.getmonth 1 enddate.setdate 0 ale...