To get the last day of a month.
Wednesday, June 25th, 2008Anybody who made a calendar in Flash may have written this code. You may use if or switch statements to get the last day of a month.
달력 같은 걸 만들면서 누구나 한번쯤 만들어 봤을 코드입니다. 지정된 달의 마지막 날을 구하기 위해서 if문이나 아래 코드처럼 switch문을 사용하게 되죠.
カレンダーみたいなものを作って見た方は、このコードを作成したことがあるんですね。普通、月の末日を得るために、if文とかswitch文を使うんです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | function getLastDayOld(day:Date):Date{ var dd:uint = 31; var yyyy:uint = day.getFullYear(); var mm:uint = day.getMonth() + 1; switch(mm){ case 4: case 6: case 9: case 11: dd = 30; break; case 2: if((yyyy % 4) == 0 || (yyyy % 100) == 0){ dd = 29; }else{ dd = 28; } break; } var lastDay:Date = new Date(yyyy, (mm-1), dd); return lastDay; } |
I figured out a more simple solution. Date.setMonth() method simply gets the job done.
그런데 이 문제를 매우 간단히 해결할 수 있는 코드를 생각해 냈습니다. Date.setMonth() 메소드 하나로 쉽게 처리가 되네요.
これをもっと簡単に処理するコードを考えてみました。Date.setMonth()メソッドを使えば、オーケーです。
1 2 3 4 5 | function getLastDay(day:Date):Date{ var lastDay:Date = new Date(day); lastDay.setMonth(lastDay.getMonth() + 1, 0); return lastDay; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | var day:Date = new Date(2008, 0, 15); for(var i:uint=0; i<12; i++){ day.setMonth(i); trace((day.getMonth() + 1), " - ", getLastDay(day).getDate(), " : ", getLastDayOld(day).getDate()); } /* output 1 - 31 : 31 2 - 29 : 29 3 - 31 : 31 4 - 30 : 30 5 - 31 : 31 6 - 30 : 30 7 - 31 : 31 8 - 31 : 31 9 - 30 : 30 10 - 31 : 31 11 - 30 : 30 12 - 31 : 31*/ |


